From 97e6a54da59591c74694bbe6f32f3419bc9ac301 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 27 Jul 2026 03:46:47 +1000 Subject: [PATCH] fix: MCP stdio transport lifecycle races and dead SendTimeout config Implement the SendTimeout config field (previously silently ignored) via a timeout-bounded write helper, and close two related races found during adversarial review: Start()/Stop() could interleave across separate lock acquisitions, and a subprocess spawned by a fresh Start() or a crash-triggered restart could clobber a StateStopped already committed and reported by a concurrent Stop(). Both spawn-commit paths now funnel through a single guarded commitSpawnedProcess. Closes archie-core-abg.17.16, archie-core-abg.17.23, archie-core-abg.17.41. --- .beads/interactions.jsonl | 5 +++ .beads/issues.jsonl | 6 +-- internal/tools/mcp/transport.go | 58 +++++++++++++++----------- internal/tools/mcp/transport_test.go | 62 +++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 27 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index a7a542b26..aa8e7621d 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -137,3 +137,8 @@ {"id":"int-50065b0a54ab73eb127ff41877f3ecda","kind":"field_change","created_at":"2026-07-26T06:58:24.455363869Z","actor":"Sam Catlow","issue_id":"archie-core-abg.22.18","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Covered by the adversarial review run when closing abg.22.9 (agent a0d701a1a058a9fe9): lockoutDuration doubling+cap verified safe, LockoutCount increment/reset paths traced correct, persistence round-trip confirmed with added test. Zero blocking findings."}} {"id":"int-802dba5ab0ca799e85b495460253b6d1","kind":"field_change","created_at":"2026-07-26T07:42:14.449273431Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.41","extra":{"field":"status","new_value":"blocked","old_value":"in_progress"}} {"id":"int-2508de6be960c7fba74de6bf16962500","kind":"field_change","created_at":"2026-07-26T17:29:24.996863094Z","actor":"Sam Catlow","issue_id":"archie-core-abg.38","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Chat-native task lifecycle implemented and adversarially reviewed; all blocking findings were false positives verified against actual code. 34 router tests + 15 controller tests covering full lifecycle. IsForgeBacked() guards daemon forge operations."}} +{"id":"int-1519f2b33e2c925537763158c89c62f9","kind":"field_change","created_at":"2026-07-26T17:43:11.314275162Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.17","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"HTTP/StreamableHTTP transport implemented and adversarially reviewed. HTTPTransport satisfies Transport interface (Send/Notify) via stateless HTTP POST, 7 tests race-clean lint-clean. One finding (missing compile-time interface assertion) fixed. Pre-existing StdioTransport test failure unrelated."}} +{"id":"int-b1cad8de3b9a95170376122128ed50ae","kind":"field_change","created_at":"2026-07-26T17:43:12.25808796Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.18","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"SSE transport implemented and adversarially reviewed. SSETransport with long-lived GET SSE connection, message ID correlation, exponential-backoff reconnection, correct goroutine lifecycle. 7 tests race-clean lint-clean, satisfies Transport interface, no blocking findings."}} +{"id":"int-79a8456ef9c42caa9babbca0e87b0e63","kind":"field_change","created_at":"2026-07-26T17:44:49.347208513Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.16","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Stdio transport implemented: JSON-RPC framing, subprocess lifecycle, auto-restart with exponential backoff. Two rounds of adversarial review found and fixed: dead SendTimeout field, Start()/Stop() TOCTOU race, and a Start()/attemptRestart-vs-Stop() race (extracted into shared commitSpawnedProcess guard). Final review: zero findings."}} +{"id":"int-73d136618f699f155055eb438881117a","kind":"field_change","created_at":"2026-07-26T17:44:50.351097372Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.23","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Adversarial review completed across two rounds; all findings fixed and re-verified clean."}} +{"id":"int-545cf6991d178c87be720cda75a8cecb","kind":"field_change","created_at":"2026-07-26T17:44:50.845655116Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.41","extra":{"field":"status","new_value":"closed","old_value":"blocked","reason":"Blocking dependency abg.17.16 closed; tool-provider engine work was already implementation-complete and previously reviewed clean."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index f478b005c..e5a9f0866 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -30,7 +30,7 @@ {"_type":"issue","id":"archie-core-abg.16.16","title":"TEST Verify: MessageType enum for gateway messages","acceptance_criteria":"TEST TASK, DELETE ME","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:11:19Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:11:25Z","closed_at":"2026-07-25T14:11:25Z","close_reason":"Test task, cleaning up","dependencies":[{"issue_id":"archie-core-abg.16.16","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:11:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.13","title":"Built-in memory tool actions: add, replace, remove","description":"Implement the three core memory tool actions: add (appends new content to a section), replace (replaces content using substring matching to find the target), remove (deletes content using substring matching). These act on the MEMORY.md/USER.md files.","acceptance_criteria":"Tool exposes three actions: add, replace, remove\nadd(target_section, content) appends to or creates a named section\nreplace(target_section, substring, replacement) finds first match of substring in section and replaces it\nremove(target_section, substring) removes the matching line/block from the section\nSubstring matching is exact, case-sensitive by default (configurable)\nActions return clear success/error messages including the affected section and character count\nTool validates section names (alphanumeric + spaces, max 64 chars)\nSize bounds are checked before any write (reject if would exceed max file size)","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:12Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:15:46Z","started_at":"2026-07-25T16:09:49Z","closed_at":"2026-07-25T16:15:46Z","close_reason":"Implemented add/replace/remove actions in memory_edit tool: section validation, substring find/replace/remove with case-sensitive/insensitive matching, size-bound pre-write checks, structured success messages with char counts.","dependencies":[{"issue_id":"archie-core-abg.18.13","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.12","title":"Built-in memory tool: file-backed persistent memory","description":"Implement the built-in file-backed memory tool that persists to MEMORY.md and USER.md files. This replaces the current ephemeral memoryNotes system with durable on-disk storage that survives restarts and sessions.","acceptance_criteria":"Built-in provider lives in internal/memory/builtin package\nMEMORY.md stores persistent agent memory (facts, preferences, state across sessions)\nUSER.md stores user-provided context (background, instructions, preferences)\nBoth files are bounded (configurable max size, default 100KB per file)\nFiles are read at provider initialization and written on every mutation\nFile format is plain markdown with sections\nThread-safe reads and writes (sync.RWMutex)\nFiles live under the profile's memory directory (e.g., ~/.config/archie/profiles/{profile}/memory/)","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:03Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:15:46Z","started_at":"2026-07-25T16:09:48Z","closed_at":"2026-07-25T16:15:46Z","close_reason":"Implemented internal/memory/builtin: file-backed Store (MEMORY.md/USER.md), size-bounded, thread-safe (sync.RWMutex), atomic writes, read-at-init via Initialize()/Reload().","dependencies":[{"issue_id":"archie-core-abg.18.12","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:03Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.17.16","title":"MCP client: stdio transport (subprocess management)","description":"Implement the MCP stdio transport: spawn and manage MCP server subprocesses, handle stdin/stdout JSON-RPC message framing, subprocess lifecycle (start/stop/restart), and auto-restart with exponential backoff. This is the foundational MCP transport that most local MCP servers use.","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:59Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:36:30Z","started_at":"2026-07-25T15:36:30Z","dependencies":[{"issue_id":"archie-core-abg.17.16","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.17.16","title":"MCP client: stdio transport (subprocess management)","description":"Implement the MCP stdio transport: spawn and manage MCP server subprocesses, handle stdin/stdout JSON-RPC message framing, subprocess lifecycle (start/stop/restart), and auto-restart with exponential backoff. This is the foundational MCP transport that most local MCP servers use.","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:59Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:44:49Z","started_at":"2026-07-25T15:36:30Z","closed_at":"2026-07-26T17:44:49Z","close_reason":"Stdio transport implemented: JSON-RPC framing, subprocess lifecycle, auto-restart with exponential backoff. Two rounds of adversarial review found and fixed: dead SendTimeout field, Start()/Stop() TOCTOU race, and a Start()/attemptRestart-vs-Stop() race (extracted into shared commitSpawnedProcess guard). Final review: zero findings.","dependencies":[{"issue_id":"archie-core-abg.17.16","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.11","title":"Tool schema normalization for memory providers","description":"Implement tool schema normalization that handles both bare tools (just Function definition) and wrapped OpenAI-style tool schemas from memory providers. Ensures all provider-exported tools are normalized to a consistent format before being merged into the agent's tool list.","acceptance_criteria":"Normalizer package detects whether a schema is bare (map with 'name' top-level) or wrapped (map with 'type':'function', 'function':{...})\nConverts both formats to a canonical internal representation\nHandles edge cases: missing required fields, extra unknown fields\nSchema normalization happens at registration time, not per-turn\nErrors on truly invalid schemas with clear messages\nRound-trips through JSON marshal/unmarshal","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:57Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:08:00Z","started_at":"2026-07-25T16:06:41Z","closed_at":"2026-07-25T16:08:00Z","close_reason":"Implemented NormalizeToolSchema + NormalizedTool in internal/memory/schema.go with full test coverage (bare, wrapped OpenAI, missing/invalid fields, JSON round-trip).","dependencies":[{"issue_id":"archie-core-abg.18.11","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.10","title":"StreamingContextScrubber","description":"Implement a stateful StreamingContextScrubber that strips \u003cmemory-context\u003e...\u003c/memory-context\u003e fence spans from streaming text output. Must handle partial chunks that split across fence boundaries, maintain state between chunks, and only emit clean text downstream.","acceptance_criteria":"Scrubber is in internal/memory/scrubber package\nImplements an io.Writer or callback interface for processing streaming chunks\nStrips \u003cmemory-context\u003e ... \u003c/memory-context\u003e fences including the tags themselves\nHandles partial chunks where fence tags span chunk boundaries (maintains state)\nHandles missing closing tags (closes at end of stream)\nDoesn't interfere with non-memory-context content\nZero allocations in the hot path (reuses buffers)\nFully tested with edge cases: partial open/close, nested tags, empty content","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:53Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:08:05Z","started_at":"2026-07-25T16:04:48Z","closed_at":"2026-07-25T16:08:05Z","close_reason":"StreamingContextScrubber implemented: io.Writer interface, handles partial chunk boundaries, nested tags, missing close tags, zero-alloc fast path. Tests + lint clean.","dependencies":[{"issue_id":"archie-core-abg.18.10","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.6","title":"MemoryManager orchestrator","description":"Implement MemoryManager that orchestrates the built-in memory provider plus at most one external provider. Key responsibilities: provider registration and lifecycle, tool schema merging from all active providers, runtime dispatch of tool calls to the correct provider, enforcement of the one-external-provider limit.","acceptance_criteria":"MemoryManager is in internal/memory/manager package\nConstructor accepts the built-in provider + optional external provider\nRegistering a second external provider returns an error\nget_tool_schemas() merges schemas from all active providers\nhandle_tool_call() routes calls to the owning provider\nProvides accessor methods for the current active provider(s)\nGracefully handles all provider being nil/empty","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:33Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:23:33Z","closed_at":"2026-07-25T15:23:33Z","close_reason":"MemoryProvider interface + optional sub-interfaces + lifecycle hooks + config helpers + backup paths + MemoryManager orchestrator implemented test-first in internal/memory/. 29 tests pass.","dependencies":[{"issue_id":"archie-core-abg.18.6","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} @@ -167,11 +167,11 @@ {"_type":"issue","id":"archie-core-abg.22.10","title":"Verify: PairingStore cryptographic code generation","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:23Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:49:24Z","closed_at":"2026-07-26T06:49:24Z","close_reason":"Covered by the adversarial review run when closing abg.22.1: crypto/rand.Int rejection sampling confirmed unbiased regardless of alphabet size, alphabet/indexing verified safe, error handling verified to never leak a malformed code. 6 tests, race-clean, lint-clean.","dependencies":[{"issue_id":"archie-core-abg.22.10","depends_on_id":"archie-core-abg.22.1","type":"blocks","created_at":"2026-07-26T00:20:28Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.22.10","depends_on_id":"archie-core-abg.22","type":"parent-child","created_at":"2026-07-26T00:12:23Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.17.20","title":"MCP client: per-server parallel tool call opt-in flag","description":"Add a per-server configuration flag to opt-in to parallel tool calls in the MCP client. When enabled, the client may dispatch multiple tool calls to the same MCP server concurrently. When disabled, all calls to that server are serialized. This respects server-side concurrency limitations.","notes":"Adversarial review complete: zero correctness findings. One scope-note (not a defect): the flag has no effect in production yet since nothing sets it -- config.MCPServer has no field for it and both NewClient call sites (main.go, internal/tools/provider/mcp/provider.go) construct clients without the option. Filed as follow-up archie-core-xec... wait wrong prefix -- archie-core-abg.17.42 (wire config -\u003e WithParallelToolCalls). This bead's own scope (the client-level mechanism: default-serialized CallTool, opt-in parallel, per-client isolation, nil-safety, deadlock-safety, race-safety) is complete and verified: go build/vet/test -race all clean, 4 tests covering default serialization, opt-in parallelism, completion correctness under serialization, and cross-client isolation.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:36:49Z","started_at":"2026-07-26T06:33:22Z","closed_at":"2026-07-26T06:36:49Z","close_reason":"Client-level mechanism complete and adversarially reviewed (zero correctness findings): Client.parallelToolCalls + WithParallelToolCalls(bool), default-serialized CallTool via a per-client mutex, opt-in removes serialization, verified nil-safe/deadlock-free/race-free. Production wiring (config.MCPServer field + both NewClient call sites) filed separately as archie-core-abg.17.42 since it's a distinct, independently-completable piece of work.","dependencies":[{"issue_id":"archie-core-abg.17.20","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.17.19","title":"MCP client: server-initiated sampling","description":"Implement MCP server-initiated sampling support: when the MCP server sends a sampling request, route it to the LLM and return the sampled response. This enables MCP servers to request LLM completions as part of tool execution (e.g. for sub-agent delegation within a tool).","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:14Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:14Z","dependencies":[{"issue_id":"archie-core-abg.17.19","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.17.18","title":"MCP client: SSE transport","description":"Implement MCP SSE (Server-Sent Events) transport: establish SSE connection to MCP servers, handle event stream parsing, manage reconnection with backoff, and translate SSE events to the unified MCP transport interface. This enables real-time streaming from MCP servers.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:30:39Z","started_at":"2026-07-26T17:30:39Z","dependencies":[{"issue_id":"archie-core-abg.17.18","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.17.18","title":"MCP client: SSE transport","description":"Implement MCP SSE (Server-Sent Events) transport: establish SSE connection to MCP servers, handle event stream parsing, manage reconnection with backoff, and translate SSE events to the unified MCP transport interface. This enables real-time streaming from MCP servers.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:43:12Z","started_at":"2026-07-26T17:30:39Z","closed_at":"2026-07-26T17:43:12Z","close_reason":"SSE transport implemented and adversarially reviewed. SSETransport with long-lived GET SSE connection, message ID correlation, exponential-backoff reconnection, correct goroutine lifecycle. 7 tests race-clean lint-clean, satisfies Transport interface, no blocking findings.","dependencies":[{"issue_id":"archie-core-abg.17.18","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.7","title":"MS Graph webhook adapter: validationToken handshake","description":"Implement MS Graph webhook adapter with validationToken handshake for subscription verification, clientState verification, and CIDR IP allowlisting.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:12Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:12Z","dependencies":[{"issue_id":"archie-core-abg.27.7","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:08:11Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.6","title":"WebhookAdapter: idempotency cache","description":"Implement TTL-based idempotency cache to deduplicate retried webhook deliveries. Cache based on webhook event ID and route.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:11Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:11Z","dependencies":[{"issue_id":"archie-core-abg.27.6","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:08:10Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.5","title":"WebhookAdapter: deliver_only mode","description":"Implement deliver_only mode that skips agent processing and directly renders the prompt template as a deliverable (e.g. plain text, HTML, JSON response).","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:08Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:08Z","dependencies":[{"issue_id":"archie-core-abg.27.5","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:08:07Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.17.17","title":"MCP client: HTTP/StreamableHTTP transport","description":"Implement MCP HTTP/StreamableHTTP transport: make JSON-RPC requests over HTTP/HTTPS with support for streamable HTTP responses. Handle connection lifecycle, keep-alive, reconnection, and error classification for remote MCP servers accessed via HTTP.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:05Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:30:38Z","started_at":"2026-07-26T17:30:38Z","dependencies":[{"issue_id":"archie-core-abg.17.17","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:05Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.17.17","title":"MCP client: HTTP/StreamableHTTP transport","description":"Implement MCP HTTP/StreamableHTTP transport: make JSON-RPC requests over HTTP/HTTPS with support for streamable HTTP responses. Handle connection lifecycle, keep-alive, reconnection, and error classification for remote MCP servers accessed via HTTP.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:05Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:43:11Z","started_at":"2026-07-26T17:30:38Z","closed_at":"2026-07-26T17:43:11Z","close_reason":"HTTP/StreamableHTTP transport implemented and adversarially reviewed. HTTPTransport satisfies Transport interface (Send/Notify) via stateless HTTP POST, 7 tests race-clean lint-clean. One finding (missing compile-time interface assertion) fixed. Pre-existing StdioTransport test failure unrelated.","dependencies":[{"issue_id":"archie-core-abg.17.17","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:08:05Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.4","title":"WebhookAdapter: prompt templates with dot-notation","description":"Implement prompt template system with dot-notation variable interpolation ({pull_request.title}, {__raw__}) for building dynamic prompts from webhook payloads.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:02Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:02Z","dependencies":[{"issue_id":"archie-core-abg.27.4","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:08:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.3","title":"WebhookAdapter: script transforms","description":"Support external script transforms per route. Allow bash/python scripts to transform incoming webhook payloads before processing.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:01Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:01Z","dependencies":[{"issue_id":"archie-core-abg.27.3","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:08:00Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-abg.27.2","title":"WebhookAdapter: declarative filters","description":"Implement declarative webhook filters with operators: all/any/not, field resolution, equals/contains/regex comparisons, and in_file lookups.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:00Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:08:00Z","dependencies":[{"issue_id":"archie-core-abg.27.2","depends_on_id":"archie-core-abg.27","type":"parent-child","created_at":"2026-07-26T00:07:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} diff --git a/internal/tools/mcp/transport.go b/internal/tools/mcp/transport.go index 85d484476..26ce9954c 100644 --- a/internal/tools/mcp/transport.go +++ b/internal/tools/mcp/transport.go @@ -350,11 +350,41 @@ func (t *StdioTransport) startSubprocess() error { t.mu.Unlock() return err } + return t.commitSpawnedProcess(cmd, stdin, stdout, false) +} +// commitSpawnedProcess installs a freshly spawned subprocess as the +// transport's active one and starts its reader goroutine. spawnProcess runs +// without t.mu held (it performs a real fork/exec), so a concurrent Stop() +// can cancel t.ctx and commit StateStopped while a spawn is still in +// flight. commitSpawnedProcess re-checks t.ctx under the lock immediately +// before committing: if Stop() already won, the just-spawned subprocess is +// discarded (killed and reaped) instead of clobbering the Stopped state +// Stop() already reported to its own caller. Both startSubprocess (a fresh +// Start()) and attemptRestart's success path (a crash-triggered restart) +// funnel through this single guarded commit point. +// +// resetStartupFailures resets the spawn-failure counter on success; it is +// true only for attemptRestart, since Start() already resets both crash and +// startup-failure counters itself before the first spawn attempt. +func (t *StdioTransport) commitSpawnedProcess(cmd *exec.Cmd, stdin io.WriteCloser, stdout *bufio.Reader, resetStartupFailures bool) error { t.mu.Lock() + if t.ctx.Err() != nil { + t.state = StateStopped + t.mu.Unlock() + _ = stdin.Close() + if cmd.Process != nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + } + return t.ctx.Err() + } t.cmd = cmd t.stdin = stdin t.state = StateRunning + if resetStartupFailures { + t.startupFailures = 0 + } t.mu.Unlock() // Start the reader goroutine. @@ -542,29 +572,11 @@ func (t *StdioTransport) attemptRestart() { continue } - // Success -- update state and start the reader. Re-check for a - // concurrent Stop() that ran while spawnProcess was in flight: if it - // already cancelled the context, discard this subprocess instead of - // reporting StateRunning for one Stop() already considers torn down. - t.mu.Lock() - if t.ctx.Err() != nil { - t.state = StateStopped - t.mu.Unlock() - _ = stdin.Close() - if cmd.Process != nil { - _ = cmd.Process.Kill() - _ = cmd.Wait() - } - return - } - t.cmd = cmd - t.stdin = stdin - t.state = StateRunning - t.startupFailures = 0 // reset on successful spawn - t.mu.Unlock() - - t.readerWg.Add(1) - go t.runReader(stdout) + // Success -- commit via the same guarded path startSubprocess uses, + // so a concurrent Stop() that cancelled the context while + // spawnProcess was in flight discards this subprocess instead of + // clobbering the Stopped state Stop() already reported. + _ = t.commitSpawnedProcess(cmd, stdin, stdout, true) return } } diff --git a/internal/tools/mcp/transport_test.go b/internal/tools/mcp/transport_test.go index 4cae28f6b..f5881f892 100644 --- a/internal/tools/mcp/transport_test.go +++ b/internal/tools/mcp/transport_test.go @@ -103,8 +103,12 @@ func (s *testMCPServer) handle(msg Message) (*Message, error) { return s.echo(msg), nil case "bad-framing": - // Write malformed output (no Content-Length) + // Write malformed output (no Content-Length header, no newline) and + // exit immediately. Without the exit, the client's reader would + // block forever inside readMessage looking for a header terminator + // that this payload never provides, hanging the test. _, _ = fmt.Fprint(os.Stdout, `{"jsonrpc":"2.0","id":1,"result":{}}`) + syscall.Exit(0) return nil, nil default: @@ -571,6 +575,62 @@ func TestStdioTransportConcurrentStartDuringStop(t *testing.T) { _ = tr.Stop(context.Background()) } +// TestStdioTransportCommitSpawnedProcessDiscardsWhenContextRacesAhead is a +// regression test for a race where startSubprocess (the path Start() uses +// to commit a freshly spawned subprocess) could clobber a StateStopped +// already committed and reported by a concurrent Stop(): spawnProcess runs +// without t.mu held (it's a real fork/exec), so Stop() can cancel t.ctx and +// return Stopped to its own caller while a spawn is still in flight. The +// commit path used to unconditionally set state = StateRunning afterward, +// wedging the transport in a Running state no caller of Stop() would ever +// expect, with no way back to Stopped. +// +// The real race is timing-dependent, so this drives the two halves +// (spawnProcess, then commitSpawnedProcess) directly and in order +// (white-box, same package) to deterministically simulate a Stop() landing +// in between them: the process is actually spawned and running (so the +// commit path's kill/reap of a live process is genuinely exercised), then +// the context is cancelled to simulate Stop() winning the race, then commit +// runs and must discard rather than clobber. +func TestStdioTransportCommitSpawnedProcessDiscardsWhenContextRacesAhead(t *testing.T) { + tr := NewStdioTransport(StdioTransportConfig{ + Command: os.Args[0], + Args: []string{"-test.run=TestMCPServerHelper$"}, + Env: []string{"GO_WANT_MCP_HELPER=1", "MCP_HELPER_BEHAVIOR=normal"}, + }) + + tr.mu.Lock() + tr.state = StateStarting + tr.ctx, tr.cancel = context.WithCancel(context.Background()) + tr.mu.Unlock() + + cmd, stdin, stdout, err := tr.spawnProcess() + if err != nil { + t.Fatalf("spawnProcess: %v", err) + } + + // Simulate a concurrent Stop() winning the race between spawn and + // commit: it would have cancelled this exact context. + tr.mu.Lock() + tr.cancel() + tr.mu.Unlock() + + err = tr.commitSpawnedProcess(cmd, stdin, stdout, false) + if err == nil { + t.Fatal("expected error when context was cancelled before commit") + } + if tr.State() != StateStopped { + t.Fatalf("state = %v, want Stopped", tr.State()) + } + + tr.mu.Lock() + gotCmd := tr.cmd + tr.mu.Unlock() + if gotCmd != nil { + t.Fatal("expected no committed subprocess after discard") + } +} + // ── Error State Tests ─────────────────────────────────────────────────── func TestStdioTransportRestartFromError(t *testing.T) {