An AI agent that talks to my car over KWP2000 and UDS
MechanIQ, the Claude agent inside the obd-scanner diagnostic app, never opens the serial port. It calls 18 typed MCP tools; deterministic code builds every CAN frame and checks every request against an allowlist of 16 service IDs. One session on a 2017 Infiniti Q50 found 13 modules and 3 stored codes, and decoded a 21-byte steering record in which 2 of 8 fields are confirmed against independent signals and 6 are labelled as inferences.
- Published
- 2026-10-28 (draft)
- Topic
- Industrial IoT
- Revision
11cc392
The agent calls tools and code builds the frames
obd-scanner is a PySide6 desktop app (Python package q50diag) that reads a car over KWP2000, UDS and OBD-II through an ELM327 or STN USB adapter. MechanIQ is a Claude Agent SDK agent in a side panel of that app. The project page describes the app, its pages and how to run it. This article covers the design decisions behind the agent's access to the car, and what one session on a car recorded.
One diagnostic read on CAN takes several steps. The adapter needs a request header and a receive filter for the module's CAN IDs. A reply longer than one frame needs ISO 15765-2 flow control and reassembly. A module that needs more time answers 7F <service> 78 (response pending), and the request has to be repeated with a longer timeout. Before any of this, something has to decide whether the service ID may be sent at all. In obd-scanner each of these steps is Python code with tests. The agent decides what to read.
The agent never receives a CAN ID or a serial handle. read_module takes a module name such as EPS. raw_read takes a module name and a hex payload such as 21 01, or an adapter command such as ATRV without a module. The tool resolves the name to a request and response ID from the vehicle profile and returns JSON: decoded values with units, codes with their status, or the request and reply as text.
The code shows three reasons for this split.
- The adapter has one owner.
Sessionruns every transport call on one worker thread. The GUI pages, parameter polling, the recorder and the agent's tools all submit commands to its queue. Inference: a second process writing to the same serial port would interleave its bytes with the session's AT commands and requests. - Code decides which bytes reach the car.
check_request_allowedruns inraw_readbefore the request is queued, and again inside the transport for every request from any caller. A model can write any hex string; the allowlist decides which ones are sent. - Results are structured, and failures say what to do next. A handler that cannot proceed raises
ToolErrorwith an instruction, for example "Not connected to an adapter. Ask the user to connect on the Connect page."
flowchart TB
model["Claude model: lead agent and 3 subagents"]
cli["Claude Code via Agent SDK, permission prompts off"]
hook{{"PreToolUse guard hook: every tool call"}}
builtin["File tools and Bash: writes inside the project only, no serial device, no secret files"]
mcp["In-process MCP server q50: 18 tools"]
gate1{{"raw_read checks the allowlist"}}
qt["Qt main thread: app state"]
pages["GUI pages and console"]
session["Session worker thread: one queue, one port owner"]
gate2{{"Transport.request checks the allowlist"}}
elm["ElmTransport: ATSH, ATCRA, flow control, ISO-TP"]
adapter["USB adapter: ELM327 or STN"]
ecu["ECUs on CAN: KWP2000, UDS, OBD-II"]
model --> cli --> hook
hook -->|"file and shell rules"| builtin
hook -->|"no rule"| mcp
mcp -->|"raw_read"| gate1 --> qt
mcp -->|"other tools"| qt
pages --> session
qt --> session
session --> gate2 --> elm --> adapter --> ecu
Transport: from a tool call to CAN frames
The adapter is set up once when the port opens: ATE0 ATL0 ATS1 ATH1 ATAT1, then the bus protocol (STP33 or ATSP6 for HS-CAN at 500 kbps), then ATCAF1 ATCFC1 ATD0 ATAL ATFCSM0. With headers on (ATH1) every reply line carries its CAN ID, so elm_parse.py reassembles single, first and consecutive frames per ID and keeps interleaved replies from two modules apart.
For each module request, ElmTransport.request checks the payload against the allowlist, then changes adapter state only where it differs from the last request: ATSH with the request ID, ATCRA with the response ID, the timeout in units of 4 ms (ATST), and flow control. Two details come from Nissan addressing and from the ELM327 command set.
- Flow control. Nissan modules on this car answer at the request ID plus 0x20; the EPS module uses 742 and 762. A comment in the driver states: "ELM's automatic OBD mapping is unsuitable for Nissan +0x20 addresses". For any pair other than 7E0 to 7E7 with a response ID 8 higher, the driver sets the flow control header itself with
ATFCSH,ATFCSD300000andATFCSM1. - Response pending. After a
7F xx 78reply the ELM prints its prompt and stops listening. The driver repeats the request once with adaptive timing off (ATAT0) and the longest timeout (ATSTFF: 255 units of 4 ms, 1.02 s), then restoresATAT1.
Adapter commands from the console or from raw_read pass to the adapter with three exceptions in console_command. Input containing a line break or a NUL byte is refused. An empty line is refused, because the ELM327 repeats the last request on an empty line. Nine command prefixes are refused, which the error message calls adapter programming and baud changes: ATPP, ATBRD, ATBRT, STP, STBR, STWBR, STSBR, STRSTNVM and VTUPDATE. The STP prefix also covers the protocol command that the app itself sends at setup. Hex lines typed on the console go through the same allowlist as every other request.
None of the 717 tests needs an adapter. tests/fake_serial.py emulates the byte stream of a vLinker FS, an OBDLink EX and a plain ELM327, and a simulator transport answers for every vehicle profile.
The services it speaks, and the ones it refuses
check_request_allowed in q50diag/core/transport.py is an allowlist keyed on the first payload byte. 16 service IDs pass it without a flag. Two more, 04 and 14 (clear codes), pass only with allow_clear=True.
| Service ID | Service | Where the app sends it |
|---|---|---|
01 02 03 05 06 07 09 0A | OBD-II read modes: live data, freeze frame, stored, pending and permanent codes, test results, vehicle information | Overview, live data and OBD-II code pages; 218 mode 01 PIDs are defined |
10 | Diagnostic session control, sub-functions 01, 03, 81, 89 and C0 only | 10 C0 (Nissan CONSULT session), falling back to 10 03, before Nissan reads; 10 81 during discovery |
17 18 | KWP2000 read codes | 18 00 FF 00 on Nissan modules. No code in the package builds a 17 request; 17 passes the gate only as a raw read from the console or raw_read. |
19 | UDS read DTC information | 19 02 FF: Nissan fallback, Ford modules |
1A | KWP2000 read ECU identification | 1A 81, 1A 87 |
21 | KWP2000 read data by local identifier | 21 83 identification, 21 01 EPS live block, explorer range 21 00 to 21 FF |
22 | UDS read data by identifier | 22 F187, F18C, F190; ABS steering angle 22 1208; Ford F190, F188, F113 |
3E | Tester present | 3E 00, the only probe sent to unknown IDs |
04 14 | Clear codes (OBD-II, KWP2000) | Trouble Codes page, after a confirmation dialog |
Everything else raises RequestBlocked. The test list BLOCKED holds 10 payloads: ECU reset 11 01, security access 27 01, write by identifier 2E 10 01, routine control 31 01, I/O control 2F 01, request download 34 00, programming session 10 02, OBD clear 04 and KWP clear 14 FF 00 without the flag, and an empty request. Each is sent to both transports through request, request_functional and raw_command, and the test asserts that the fake serial port received no bytes. A separate test sends 5 payloads (reset, security access, write by identifier, clear without the flag, routine control) through raw_read, and another refuses OBD mode 08 (on-board test control, which actuates components) in 2 forms.
The agent cannot clear codes. raw_read calls the allowlist without the flag, and the session forwards the agent's request to the transport without it. The only caller that sets allow_clear=True is the clear routine started from the Trouble Codes page after the user confirms a dialog.
Module discovery follows the same rule. Each of the 15 addresses in the Q50 profile is probed with 3E 00, 10 81 and 21 83 until one gets a positive reply. The remaining IDs from 0x700 to 0x7FF get tester present only; the code comment reads "Unknown addresses get tester present only, so no session is started on them." The sweep never transmits on a response ID or on 0x7DF.
The allowlist call lives in each transport implementation, ElmTransport and SimulatedTransport. The abstract Transport.request states the contract in its docstring, and the parametrized test covers both implementations. Inference: a third transport would need its own call and its own test case.
18 tools in the app's own process
build_mcp_server creates an in-process MCP server named q50 with the Agent SDK's create_sdk_mcp_server. The tools are methods on the running app, and the agent sees them as mcp__q50__<name>. Because they run in the app's process, they read the same parameter store, recorder and event markers that the GUI shows, and their vehicle requests enter the same session queue as the pages' requests.
The handlers run on the SDK's asyncio thread. Every read or change of app state is moved onto the Qt main thread with call_in_main_thread, wrapped in asyncio.to_thread so that neither the Qt thread nor the asyncio loop blocks. Tools whose result arrives as a session signal connect a one-shot catcher, submit the command and wait with a timeout: 8 s for raw_read, 45 s for read_module and 120 s for scan_dtcs.
| Group (this article's grouping) | Tools | Names |
|---|---|---|
| App state, no vehicle traffic | 4 | get_status, list_parameters, get_readings, get_dtcs |
| Vehicle requests | 3 | scan_dtcs, read_module, raw_read |
| Polling and event marks | 5 | start_polling, stop_polling, start_steering_watch, stop_steering_watch, mark_event |
| Recordings and log | 3 | list_recordings, read_recording, read_app_log |
| GUI | 1 | navigate |
| Code changes | 2 | apply_change, undo_change |
The lead agent can start three subagents. code-fixer edits code. data-analyst and test-coach have Edit, Write, NotebookEdit, apply_change and undo_change in their disallowed tools. test-coach also has Bash in that list. data-analyst keeps Bash, which its prompt allows for read-only Python statistics in a source checkout.
The vehicle profile writes the car section of the system prompt. For the Q50 it carries the field findings described below: the EPS address, the 21 01 byte layout with each unconfirmed field marked "(inferred)" or "candidate", the gatewayed OBD port and the stored codes. The prompt's style section ends: "Label inferences as inferences."
One tool lets the agent change the app itself. apply_change runs the related tests with pytest -q -x (300 s timeout), hot reloads the changed modules and commits only the listed files locally as fix(mechaniq): <summary>. A failing test stops it before the reload and the commit.
The guard hook
The runner starts the Claude Code session with permission_mode="bypassPermissions" and one PreToolUse hook. With no permission prompts, the hook decides every tool call. The docstring of guard.py states it: "MechanIQ runs with permission prompts off, so this hook is the hard boundary." The hook is registered without a matcher, so it receives every call. It has rules for 9 tool names (4 write tools, 3 read tools, Bash and PowerShell) and returns no decision for the rest, which includes the 18 q50 tools and Task.
| Rule | Checked in | A denied input from the tests | Cases |
|---|---|---|---|
| File writes outside the project | Write, Edit, MultiEdit, NotebookEdit | NotebookEdit on /tmp/n.ipynb | 5 |
| Bash writes outside the project | Bash redirects and tee | ls | tee /tmp/listing.txt | 4 |
| Serial device access | Bash | screen /dev/ttyUSB0 115200 | 6 |
.env files and the settings file | Read, Grep, Glob, Bash, Write | source ./.env && pytest | 12 |
git push | Bash | cd q50diag && git push | 4 |
git reset --hard, git clean | Bash | git status; git clean -n | 4 |
| PowerShell | PowerShell | Get-ChildItem | 1 |
The 7 deny rules account for 36 cases. 22 more are allow cases, which act as controls: a guard that denied everything would fail them. The last 4 test the hook plumbing: other hook events pass through, relative paths resolve against the working directory, unbalanced quotes fall back to text checks, and segments split on separators. The project page charts the deny and allow counts. One of them is the commit git commit -m "fix(mechaniq): push EPS reads earlier; COM5 note; reset --hard docs", whose message contains the words of three deny rules.
The Bash rules work on parsed commands. shell_segments splits a command with shlex into simple commands at ;, |, &, parentheses and line breaks, so quoted text stays inside its argument. For a segment that runs git, the subcommand is found after git's own options, which is how git -C /x push --force is caught. The serial patterns (/dev/tty, /dev/serial, COMn, serial.Serial(, serial_for_url, miniterm) apply to segments that do not run git. Redirect and tee targets are resolved against the working directory and checked as file writes; /dev/null, /dev/stdout, /dev/stderr and $VARIABLE targets are skipped. The secret check runs on the raw text before shlex, with backslashes turned into slashes, because shlex drops the backslashes of an unquoted Windows path. A command with unbalanced quotes falls back to regular expressions for push, discard and serial access.
Each denial names what to do instead. The serial rule returns: "Bash may not open a serial device or adapter port: the q50diag app owns the connection. Use the q50 tools (raw_read, read_module, get_readings) for vehicle access. To search code for this text, use the Grep tool." Inference: the last sentence covers a code search whose text matches a serial pattern, such as a search for /dev/tty; a Grep call for serial.Serial is one of the allowed test cases.
The same docstring states the limit: "The Bash checks are a guard against mistakes, not a sandbox: a script file can still do anything its interpreter allows."
One session on a 2017 Q50: modules and codes
On 2026-10-17 the app was connected to a 2017 Infiniti Q50 3.0t through a vLinker FS r2 adapter (STN1170 firmware v4.3.2) at 115200 baud, about 16 ms per command. The complaint was steering that intermittently feels stiff and sluggish. The car has no DAS: its Drive Mode Selector offers Standard and Sport steering only, and there is no power steering fluid reservoir, so it has a rack electric power steering (EPS) unit.
Every field value in this article comes from docs/q50-findings-2026-10-17.md. That document records what was read and decoded. It does not record which requests MechanIQ issued and which came from the GUI pages or the console, and this article makes no claim about the agent's share of the session.
A 65 s discovery sweep found 13 modules.
| Module | Request/response ID | Stored codes |
|---|---|---|
| ECM, TCM | 7E0/7E8, 7E1/7E9 | none |
| EPS | 742/762 | none |
| ABS | 740/760 | none |
| RADAR | 723/735 | C1A01-00, C1A16-00 |
| AIR BAG | 752/772 | B00A0-00 |
| METER, HVAC, BCM, AV, IPDM, TPMS | 743, 744, 745, 747, 74D, 758 | none |
| Unknown | 7F1/7F9 | Answers tester present only. The document labels "possibly the CAN gateway" as an inference. |
12 of the 15 addresses in the Q50 profile answered. AWD (748), STEERING ANGLE (75C) and ADAS (707) did not.
Two modules store three codes, each with status 0x08: confirmed, not currently failing. The EPS, ECM and ABS store none. The engine has the MIL off, 0 OBD-II codes and all readiness monitors complete. The repository ships no trouble code descriptions. The app reads them from a file the user supplies, and a code with no entry in that file shows an empty description. The document states that the Q50 meanings of the three stored codes need the factory service manual.
The OBD port on this car is gatewayed. An unfiltered 5 s bus monitor received 0 broadcast frames, so every value in the session was polled from a module. The Q50 prompt notes pass this to the agent, with broadcast IDs such as 0x002, 0x300 and 0x5E4 listed as not readable at the port.
One session on a 2017 Q50: the steering record
The EPS module answered Nissan local identifiers (21 xx) only; six 22 xxxx ranges returned nothing. The project's research notes state that no public source gives EPS identifiers for the Q50. 21 06 returned a 280-byte block, which the document labels an inference: a stored event history, not decoded.
The 21-byte live block 21 01 was decoded from 97 samples with the wheel at rest and 215 samples during lock-to-lock turns, compared with the steering angle that the ABS module reports through 22 1208. The confidence column is copied from the findings document.
| Bytes | Meaning | Confidence | Observed |
|---|---|---|---|
| 0 to 1 | Supply voltage, x 4 mV | Matches ATRV | 14.0 to 14.25 V at rest, 13.26 V pushing into full lock |
| 3 to 4 | Steering angle, signed, x -0.1 deg | Correlation -1.00 with ABS angle | -543 to +553 deg |
| 5 to 6 | Steering velocity, signed | Inferred | About -3.7 deg/s per count, 0 when held |
| 7 | Assist load | Inferred | 0 at rest, up to 25 at full lock |
| 8 | Driver torque, signed | Inferred | +49 holding left lock, -59 pushing right lock |
| 10 | Temperature candidate | Inferred | Rose from 45 to 53 as the car warmed |
| 11 | Assist limit candidate | Inferred | 100 in every sample |
| 15 to 16 | Motor speed candidate, signed | Inferred | 0 at rest, about -3 counts per deg/s of steering rate |
Two fields are confirmed against an independent signal: the supply voltage matches the adapter's ATRV reading, and the angle correlates at -1.00 with the ABS angle. The other six are inferences. The labels carry into the code. The unconfirmed fields are named with "raw" or "candidate", for example "EPS byte 11 (raw, assist limit candidate)", and the description of each unconfirmed field ends with "Inferred from a wheel-turn capture; scale unconfirmed."
A worked example, computed for this article: the simulator keeps the 21 01 reply that the car returned at rest, 0D BD 02 00 8F 00 00 00 00 00 35 64 00 00 60 00 00 00 00 00 00. The app's decoders read it as follows. Bytes 0 and 1, 0x0DBD, are 3517 counts of 4 mV, 14.068 V, inside the 14.0 to 14.25 V the document gives at rest. Bytes 3 and 4, 0x008F, are 143 counts of -0.1 deg, -14.3 deg. Bytes 7 and 8 are 0. Byte 10 is 0x35, 53. Byte 11 is 0x64, 100. Bytes 15 and 16, the motor speed candidate, are 0.
One session on a 2017 Q50: live data, drive and outcome
| Value | Source | Observed |
|---|---|---|
| Battery voltage, engine running | ATRV | 14.0 to 14.5 V (drive and parked) |
| ECM module voltage | PID 42 | 13.44 to 13.84 V |
| Coolant, warm idle | PID 05 | 97 to 99 degC |
| Idle speed | PID 0C | 638 to 650 rpm |
A 330 s drive recording has 3 "Steering felt heavy" marks: at 5 s (stopped, -15 deg), at 31 s (2 km/h, +533 deg, near full lock) and at 57 s (36 km/h, -8 deg). Voltage at all three marks was 14.0 to 14.3 V, and the document concludes that low voltage is excluded as the cause of those events. The recording has no EPS data, and speed and angle were sampled only every 3.7 s, so assist at the marks is unknown. The recording is not in the repository.
The document's summary for the complaint: the EPS module stores no codes; during the parked wheel-turn test the supply voltage stayed above 13.2 V, assist rose with steering effort, and the assist limit candidate stayed at 100 in every sample. No captured value shows an EPS fault. The complaint was not reproduced during a capture that included EPS data.
The next steps it lists are a drive with the rebuilt Steering page recording, which includes EPS assist, torque and assist limit, and a lookup of the three codes in the Q50 service manual. If a marked event then shows normal assist load and no limit reduction, the document states that the cause is likely outside the EPS electronics. It names tire pressure, alignment, tie rods and rack friction as candidates, labels them inferences, and states that none of them was measured.
Limits
Not tested on hardware
- Field data covers one car, one adapter and one session, on 2026-10-17.
- The two Mustang S550 profiles (9 modules each) come from public address lists. The repository holds no field capture from a Mustang.
- MS-CAN on the vLinker FS is untested. The OBDLink EX and plain ELM327 support is tested against emulated byte streams only.
- The sample rate of the rebuilt Steering page recording on the car is not yet measured.
- The simulator replays a 90 s drive cycle: idle to 15 s, acceleration to 95 km/h by 40 s, cruise to 70 s, deceleration to 90 s. Apart from the stored EPS record, its values are synthetic and say nothing about the car.
Read-only by allowlist
- No write, reset, security access, routine, I/O control, download or programming service is on the allowlist. Codes can be cleared only from the Trouble Codes page after a confirmation dialog. The agent has no tool that clears codes.
- Adapter commands are filtered by a list of refused prefixes, which is a block list. Any AT, ST or VT command outside that list reaches the adapter, including from
raw_read.
Inferred fields
- Six of the eight decoded EPS fields in the findings document are inferences, and their scales are unconfirmed.
- The steering complaint was not reproduced while EPS data was captured, so no decoded field has yet been observed during a heavy steering event.
The guard hook
- The hook is designed to catch agent mistakes. A script the agent writes inside the project can do anything its interpreter allows. Reads outside the project are allowed, except of the secret files; one allowed test case reads a dotfile in the home directory. Permission prompts and an operating system sandbox are not used.
data-analystandtest-coachare denied the edit tools andapply_change;test-coachis also denied Bash.data-analystkeeps Bash, and a Bash redirect inside the project passes the guard, so its read-only role inside the project rests on its prompt. The disallowed lists omitMultiEditbecause the Claude Code CLI bundled with the pinned Agent SDK has no such tool; the guard still checks it as a write tool.- The findings document does not record which requests the agent made during the field session.