Mitchell Foutz All writing

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
Source
darblinko/q50-obd-scanner
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.

  1. The adapter has one owner. Session runs 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.
  2. Code decides which bytes reach the car. check_request_allowed runs in raw_read before 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.
  3. Results are structured, and failures say what to do next. A handler that cannot proceed raises ToolError with an instruction, for example "Not connected to an adapter. Ask the user to connect on the Connect page."

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.

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 IDServiceWhere the app sends it
01 02 03 05 06 07 09 0AOBD-II read modes: live data, freeze frame, stored, pending and permanent codes, test results, vehicle informationOverview, live data and OBD-II code pages; 218 mode 01 PIDs are defined
10Diagnostic session control, sub-functions 01, 03, 81, 89 and C0 only10 C0 (Nissan CONSULT session), falling back to 10 03, before Nissan reads; 10 81 during discovery
17 18KWP2000 read codes18 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.
19UDS read DTC information19 02 FF: Nissan fallback, Ford modules
1AKWP2000 read ECU identification1A 81, 1A 87
21KWP2000 read data by local identifier21 83 identification, 21 01 EPS live block, explorer range 21 00 to 21 FF
22UDS read data by identifier22 F187, F18C, F190; ABS steering angle 22 1208; Ford F190, F188, F113
3ETester present3E 00, the only probe sent to unknown IDs
04 14Clear 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)ToolsNames
App state, no vehicle traffic4get_status, list_parameters, get_readings, get_dtcs
Vehicle requests3scan_dtcs, read_module, raw_read
Polling and event marks5start_polling, stop_polling, start_steering_watch, stop_steering_watch, mark_event
Recordings and log3list_recordings, read_recording, read_app_log
GUI1navigate
Code changes2apply_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.

RuleChecked inA denied input from the testsCases
File writes outside the projectWrite, Edit, MultiEdit, NotebookEditNotebookEdit on /tmp/n.ipynb5
Bash writes outside the projectBash redirects and teels | tee /tmp/listing.txt4
Serial device accessBashscreen /dev/ttyUSB0 1152006
.env files and the settings fileRead, Grep, Glob, Bash, Writesource ./.env && pytest12
git pushBashcd q50diag && git push4
git reset --hard, git cleanBashgit status; git clean -n4
PowerShellPowerShellGet-ChildItem1

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.

ModuleRequest/response IDStored codes
ECM, TCM7E0/7E8, 7E1/7E9none
EPS742/762none
ABS740/760none
RADAR723/735C1A01-00, C1A16-00
AIR BAG752/772B00A0-00
METER, HVAC, BCM, AV, IPDM, TPMS743, 744, 745, 747, 74D, 758none
Unknown7F1/7F9Answers 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.

BytesMeaningConfidenceObserved
0 to 1Supply voltage, x 4 mVMatches ATRV14.0 to 14.25 V at rest, 13.26 V pushing into full lock
3 to 4Steering angle, signed, x -0.1 degCorrelation -1.00 with ABS angle-543 to +553 deg
5 to 6Steering velocity, signedInferredAbout -3.7 deg/s per count, 0 when held
7Assist loadInferred0 at rest, up to 25 at full lock
8Driver torque, signedInferred+49 holding left lock, -59 pushing right lock
10Temperature candidateInferredRose from 45 to 53 as the car warmed
11Assist limit candidateInferred100 in every sample
15 to 16Motor speed candidate, signedInferred0 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

ValueSourceObserved
Battery voltage, engine runningATRV14.0 to 14.5 V (drive and parked)
ECM module voltagePID 4213.44 to 13.84 V
Coolant, warm idlePID 0597 to 99 degC
Idle speedPID 0C638 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

Read-only by allowlist

Inferred fields

The guard hook