- 5 cases at the dispatch routing boundary: in-process route, stdio fallthrough,
confirmation gate preservation, late-registration timing, observer parity.
- All FAIL until InProcessAwareToolDispatcher composite + InProcessConfirmationCache land.
- Bug: B-01 wired catalog enumeration (10-02b) but missed dispatch routing —
MCPToolDispatcher only knows the 3 stdio tools, so when the model emitted
tool_use for get_active_audio_route, dispatch failed and the failure
surfaced as visible chat text.
Adds the substrate that the production fix at App/AppDelegate.swift:1274
needs to source the tool catalog from the in-process registry instead of
the hardcoded empty array.
Protocol change:
- InProcessTool gains `var toolDescription: String { get }` — a
human-readable one-line description surfaced in the Anthropic / Ollama
tools[] payload's `description` field. Named `toolDescription` (not
`description`) to avoid colliding with CustomStringConvertible.
All 7 production InProcessTool implementations updated with descriptions
calibrated to drive correct tool selection by the model:
- list_audio_devices, get_active_audio_route, get_self_state,
list_camera_devices (Phase 10-01 self-knowledge tools)
- search_memory, forget_fact, search_conversation (Phase 7 memory tools)
Registry change:
- InProcessToolRegistry.toolSchemas() projects every registered tool to
a ToolSchema(name, description, inputSchema) suitable for the LLM
request body. Returns name-sorted for prompt-cache determinism.
- Adds AgentCore import to InProcessToolRegistry for the ToolSchema type.
Test coverage:
- InProcessToolRegistrySchemasTests asserts all 7 tools project
correctly with non-empty descriptions and inputSchema bytes.
- All 85 existing MCP tests pass unchanged.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- ListAudioDevicesToolTests, GetActiveAudioRouteToolTests,
GetSelfStateToolTests, ListCameraDevicesToolTests — Stub-style
dispatchers (D-31) drive each tool through its JSON encode path.
- MCPRuntimeWiringTests/registersFourSelfKnowledgeTools — asserts the
four tool names register in InProcessToolRegistry AND each carries
requiresConfirmation == false (D-10).
- All five fail to compile until Task 2 ships the production types
(AudioDeviceListing/Entry, ActiveAudioRouteDispatching/Route,
SelfStateDispatching/State, CameraDeviceListing/Entry, four tool
structs). RED confirmed via `cannot find type ...` diagnostics.
Per audit-2026-05-04 P2-14: VoiceController._forceState,
_testFireSpeechEnd, _testCurrentSttSessionId were declared `public`
solely so XCTest could see them. Same for MCPClient._testHandle and
MCPServerHandle._testProcessIdentifier. These leaked test-only entry
points into each package's public API — anyone importing Voice could
call _forceState(.speaking) from production code.
Voice (4 seams): public → internal. Voice tests already use
@testable import Voice, so no test-side change required.
MCP (2 seams): public → @_spi(Testing) public. MCP tests opt in
via @testable @_spi(Testing) import JarvisMCP. The Harness package
(non-test) consumes _testHandle / _testProcessIdentifier for the
MCPCrashRunner SIGKILL recipe — opt in via @_spi(Testing) import.
@testable alone does NOT expose @_spi symbols — the SPI must be
explicitly imported, which is the desired discipline (each consumer
acknowledges they're reaching past the public ABI).
6 test seams total moved off the public ABI. Voice + MCP tests
pass (87 + 85). Harness builds clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
[Rule 3 - Blocking] VllmMlxSidecar (Task 4) needs ChildSpawnGate but
packages/Vision can't depend on JarvisMCP without transitively pulling
AgentOrchestrator (which would violate VISION-03 boundary).
Solution: hoist ChildSpawnGate.swift into a new JarvisChildSpawn SPM
target inside the MCP package. JarvisMCP keeps the same singleton via
the new dep; Vision can now depend on JarvisChildSpawn alone.
- New target JarvisChildSpawn (only depends on swift-log)
- JarvisMCP gains JarvisChildSpawn as a dependency
- MCPServerHandle.swift / MCPClient.swift gain 'import JarvisChildSpawn'
- ChildSpawnGate uses Logger directly instead of MCPLogChannel.logger
(avoids dragging MCPLogChannel into the standalone target)
- Tests updated to '@testable import JarvisChildSpawn'
- All 3 ChildSpawnGate tests pass; full MCP build clean
Match the SDK's `Client.callTool(name:arguments:)` signature where
`arguments: [String: Value]?` is optional. Callers can now invoke
no-arg tools without manually passing `[:]`. MCPToolDispatcher now
preserves the JSON-RPC `arguments: null` vs `arguments: {}`
distinction by passing `nil` when the model emits no args bytes.
Updated MCPClientCalling protocol + MockClient conformer in
MCPToolDispatcherTests to match the optional shape. Added
test_callTool_withoutArguments_isAccepted that exercises the default
nil parameter.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Replaced `try? await Task.sleep + Task.isCancelled` with an explicit
do/catch that early-returns on CancellationError. Previously the
`try?` swallowed the cancellation error and a window opened between
sleep returning and Task.isCancelled being observed during which a
cancelled timer could still fire .timeout. Today the broker's
first-write-wins guard saves us, but a future contributor removing
that guard would silently introduce double-resolve.
Adds test_response_atTimerBoundary_firstWriteWins_noDoubleResolve —
loops 10x at a 50ms timeout, sends .deny at T+49ms, asserts the
broker resolves exactly once (deny OR timeout, both legal) and dismiss
fires exactly once. Catches double-resolve regressions.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Previously ConfirmationPresenter held broker as `weak var` and
ConfirmationPresenterHolder held its inner presenter as `weak var` —
a doubly-weak chain that could silently break Approve/Deny button
responses if either side deinit'd during a pending request. The user
would see the panel close on Approve, then the orchestrator would
hang for 60s until the broker's timer fired .timeout.
Switched both to strong references. The cycle motivation
(broker → presenter → broker) is broken by the holder indirection:
broker holds the holder, holder holds presenter strongly, presenter
holds broker strongly. The chain is acyclic when read top-down because
the broker does not hold the presenter directly.
Documents the lifecycle invariant on MCPRuntime: AppDelegate must hold
runtime strongly for the lifetime of the process; orchestrator must
not outlive the runtime.
Adds ConfirmationLifecycleTests with three guards:
- canonical hold pattern always resolves Approve
- wedged presenter (never calls broker.response) still resolves via
timeout — the timer is the load-bearing fallback
- source-level: ConfirmationPresenter declares `let broker:` (strong),
not `weak var broker:`
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
LSBackgroundOnly: true silently denied NSPasteboard.general access on
macOS Sonoma+ (Apple feedback FB13402281 lineage). LSUIElement: true
already suppressed the Dock icon — both keys together were redundant
and one was actively breaking pasteboard reads. Removed
LSBackgroundOnly per Option A in REVIEW 05; LSUIElement stays.
Adds test_get_clipboard_seeded_returnsSeededString_CR04 that seeds
NSPasteboard.general with a UUID-tagged string in the parent test
process, then asserts the helper's response is EXACTLY that string
(not the silent-empty marker that the pre-fix LSBackgroundOnly
configuration produced). Skips on headless CI where the parent
can't write the pasteboard.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
CR-03: BusGateway's toolUseId parameter is now String (matching the bus
schema's Phase 2 closed contract) instead of UUID. Previously the
dispatcher synthesized `UUID(uuidString: toolUse.id) ?? UUID()`, which
silently produced a fresh random UUID for every Anthropic 'toolu_…' or
Ollama free-form id — breaking correlation across bus / replay /
orchestrator. The original String id now flows verbatim from
toolCallStart through argsPreviewUpdate to toolCallEnd. The broker's
internal UUID is now a fresh-per-call value and does NOT replace the
bus-facing id.
WR-04: ConfirmingToolDispatcher now emits toolCallEnd(ok: true, …) on
the success path so bus consumers (HUD ToolCallCard) transition
Running → Completed. On dispatch error post-approval, toolCallEnd
fires with ok: false carrying the error description before re-throwing.
Adds three new tests (busToolUseId verbatim across emissions, non-UUID
id flows through, success path emits 3 events). Updates SpyBus and
SpyBus-equivalent in MCPRuntimeWiringTests to use String toolUseId.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Both initialize-failure throw arms in MCPServerHandle.start() (the
client.connect() catch and the helperMissingToolsCapability guard) now
call a new closeParentPipeEnds helper before throwing. Without this,
each failed start() leaked 3 parent-side pipe FDs (stdin write, stdout
read, stderr read) — Foundation's Pipe deinit doesn't close FDs when
the underlying FileHandle was created with closeOnDealloc:false (the
default), and terminateProcessImmediately only SIGKILLs the child.
Adds MCPServerHandleInitFailureFDLeakTests with four structural
assertions: helper exists, closes all three retained ends, both throw
arms call it, cleanup precedes the throw on both arms.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Closes MCP-04 (full args-redaction seal pre-approval) and SEC-08
(defense-in-depth args masking on the bus). Final wiring of AGENT-11's
timeout-as-deny semantics — .timeout outcome triggers a JarvisLogChannel.mcp
WARNING line + ConfirmationError.timedOut throw.
- Public actor ConfirmingToolDispatcher conforms to ToolDispatcher and
composes around an inner ToolDispatcher (production: MCPToolDispatcher).
Plan 04-04's orchestrator code is unchanged; the gating happens by
composition.
- Pre-approval bus emission's argsPreview is the literal
'{"awaitingApproval":true}' seal. Post-approval, a follow-up
updateArgsPreview carries the sanitized real args.
- BusGateway protocol abstracts the three bus surfaces the dispatcher
needs (start / update / end). App-level wiring implements it.
- defaultLogWarning routes to swift-log Logger(label: 'mcp') with a
'subsystem=ConfirmingToolDispatcher' metadata key. Tests inject a
recording closure.
- 9 tests: pass-through fast path; awaiting-approval seal ordering;
approve / deny / timeout / barge outcomes; inner-error propagation
after approval; sync requiresConfirmation delegation; explicit
args-redaction-before-approval invariant. test_OC_T1_timeoutLogsWarning
name fixed by plan medium-finding.
Closes MCP-09 (broker FSM, first-write-wins on .approve / .deny / .timeout
/ .barge) and AGENT-11 (60s timeout-as-deny via Task.sleep with sub-second
test-injection knob).
- ConfirmationOutcome.swift defines the four-outcome enum, matching
ConfirmationError throw-type, and ConfirmationPresenting protocol so the
broker can compile + test against an actor mock without pulling AppKit.
- ConfirmationBroker.swift is a public actor whose serial executor IS the
synchronization primitive; no locks, no atomics. The 'resolved' guard
inside response(id:outcome:) enforces MCP-09 first-write-wins.
- 9 tests cover the four-outcome happy paths, the sub-second timeout, the
late-hop no-op invariants (after .approve and after .timeout), the
concurrent-response race, the unknown-id no-op, and the dismiss-once
lifecycle invariant.
8 tests covering the ToolDispatcher conformance:
- happy-path text concat + sanitize (zero-width + bidi stripped)
- multi-block .text concatenation
- under-cap passthrough vs over-cap boundary marker
- error propagation from client
- synchronous (nonisolated) requiresConfirmation read
- ToolResultObserver receives both pre- and post-sanitize bytes
- observer NOT called on error
Adds the asymmetric MCP→AgentCore SPM dependency (MCP imports
AgentCore + AgentOrchestrator; AgentCore intentionally does NOT
depend on MCP — the orchestrator stays provider-agnostic and only
sees the protocol). This deviates from Plan 05-01's stated isolation
of MCP from AgentCore; the deviation is the intentional bridge
between the two packages. No cycle.
5 tests covering register / unknown / requiresConfirmation /
toolNames-sorted / overwrite-existing semantics. ToolRegistry is
the value-type snapshot MCPToolDispatcher captures at init so the
protocol's nonisolated requiresConfirmation(toolName:) can read
synchronously without an actor hop.
18 tests covering the byte-stream sanitize + head-truncate boundary:
- C0/DEL/bidi-override/bidi-isolate/zero-width/BOM stripping
- per-line cap at 4096 bytes with `…[line-truncated]` marker
- newline preservation (split-first pattern)
- UTF-8 totality on garbage input
- head-truncate cap (8192) with byte-count marker
- prepareForBoundary fixed-order guard (sanitize → headTruncate)
using a 10000→2500-byte distinguisher input that proves the
reverse order would leak a truncation marker
- prepareForBoundary does NOT wrap (wrap is orchestrator-side)
project.yml:
- Register swift-sdk @ 0.12.0 as a top-level package (consumed by both
helper targets; same exact version as packages/MCP/Package.swift)
- Add mcp-time and mcp-clipboard application targets with per-config
signing (Debug=ad-hoc CODE_SIGNING_ALLOWED=NO, Release=hardened
runtime + --options=runtime --timestamp). Each target carries its
own CODE_SIGN_ENTITLEMENTS pointing at mcp-servers/<helper>/Support/
- Each helper has a postBuildScript that copies its source
.entitlements into <bundle>/Contents/Resources/ where codesign.sh
expects it (per P1-05 contract)
- Jarvis target depends on both helpers (embed=false, link=false —
helpers are independent .app subprocesses, not linked frameworks)
DEVIATION (Rule 3, blocking issue): xcodegen 'copyFiles' phase doesn't
resolve target products from BUILT_PRODUCTS_DIR — it expects file
paths relative to SRCROOT. The plan's
'files: [mcp-time.app, mcp-clipboard.app]' produced an empty
Contents/Helpers/ at build time. Switched to a postBuildScript on
Jarvis ('Copy MCP helpers into Contents/Helpers/') that 'cp -R' from
BUILT_PRODUCTS_DIR. This matches the plan's deviation_rules clause #1
('If xcodegen doesn't directly support nested .app bundles via
Contents/Helpers/<Name>.app/, generate the helper bundles via
separate xcodebuild targets and copy them in via a Build Phase
script.'). Code Sign On Copy stays disabled — codesign.sh's
deepest-first walker is the authoritative signer.
DEVIATION (Rule 1, bug): mcp-time/Sources/mcp-time/main.swift renamed
to MCPTimeMain.swift to fix Xcode's '@main attribute cannot be used
in a module that contains top-level code' error. Same root cause as
mcp-clipboard's earlier rename — when the file is named main.swift,
Xcode treats it as a script and rejects @main on a struct.
Standalone 'swift build' tolerated it; xcodebuild does not.
Integration tests (packages/MCP/Tests/MCPTests/):
- HelperBundleLocator.swift: shared resolver, env override →
Bundle.main walk → DerivedData walk (Release-preferred; skips Debug
builds with adjacent <helper>.debug.dylib because Xcode 26's
incremental-link artifact has a code signature mismatch with the
parent and dyld rejects on subprocess launch)
- MCPTimeIntegrationTests: round-trip get_time, parse via
ISO8601DateFormatter, assert ±60s of Date()
- MCPClipboardIntegrationTests: round-trip get_clipboard, accept any
of (text/empty/refusal) outcomes since the test runner's pasteboard
state is unknown
DEVIATION (Rule 1, bug): Both integration tests use synchronous
'await client.shutdown()' rather than 'defer { Task { await ... } }'.
Fire-and-forget shutdown leaks helper stdio FDs into the next test;
ChildSpawnGate's DEBUG-only fatalError precondition (FD must be
CLOEXEC) crashes the next spawn. Discovered when MCPRestartTests ran
after the integration tests in the same suite.
Verification:
- swift test --package-path packages/MCP: 18/18 pass (16 from 05-01
+ 2 new integration). FD leak baseline=4 final=4 delta=0
- swift test --package-path mcp-servers/mcp-clipboard: 6/6 pass
- xcodegen generate: clean
- xcodebuild Release build: SUCCEEDED end-to-end (codesign + verify)
- Both helper bundles signed with empty entitlements; 0 apple-events
- 0 CodeSignOnCopy=YES, 0 --deep in pbxproj
- MCPServerHandle.claimOrShareRestart(buildTask:): atomic claim-or-share
primitive that runs entirely under handle actor isolation. The closure-
based design ensures the Task is only constructed inside the actor's
serial execution, so concurrent callers can't race past the slot check
and stampede the spawn path.
- MCPClient.callTool: layers the per-server mutex on top —
1. await any in-flight restart; then
2. if still crashed, claim-or-share the slot (claimant runs start();
sharers await the same task);
3. dispatch through the SDK client.
Slot is cleared on both success and failure paths so a future call
after a failed restart can attempt again. No backoff/retry inside the
mutex — RESEARCH A5 contract.
- MCPServerHandle.start: pin PID at terminationHandler wire time so a
STALE handler from a prior helper (post-restart) cannot flip
isCrashed=true on the LIVE process; handleTermination(forPID:) early-
returns when self.process.processIdentifier != pid.
- MCPServerHandle.start: set FD_CLOEXEC on the parent-side pipe ends
(stdin write, stdout read, stderr read) immediately after Process.run().
Foundation creates Pipe FDs without O_CLOEXEC; without this retrofit
the Debug-build ChildSpawnGate fatalErrors when a subsequent spawn
sweeps the parent FD table. CLOEXEC at FD-creation time is the gate's
primary defense per RESEARCH Pitfall #8.
- MCPRestartTests: 4 tests
1. test_singleCrash_followedBy_callTool_succeedsAfterRestart
2. test_concurrentCallsDuringRestart_shareOneRestart (8-way contention,
tally side-channel verifies exactly 2 helper starts: initial + 1 restart)
3. test_inFlightCallTool_duringCrash_throws_serverCrashed (mock_slow
call SIGKILL'd mid-flight)
4. test_100_crashCycles_noFDLeak (baseline=4, final=4, delta=0)
Plan: 05-01 Task 3 of 3.
- MCPServerHandle actor: spawns helper via ChildSpawnGate.shared.prepare(),
sets process.environment = minimalEnvironment, launches with 3 Pipes,
closes child-side pipe ends in the parent (FD-leak guard for restart
cycles), wires StdioTransport with EXPLICIT FileDescriptor args (single-
line so the grep gate matches literally), connects SDK Client, asserts
Initialize.Result.capabilities.tools != nil, drains stderr to log channel,
installs terminationHandler -> handleTermination async path.
- MCPServerHandle.callTool wraps the SDK's (content, isError?) tuple back
into CallTool.Result so downstream consumers see the documented type.
Errors during a call are translated to JarvisMCPError.serverCrashed only
when isCrashed is set; otherwise rethrown verbatim.
- MCPClient actor: registry of MCPServerHandle keyed by server name,
toolToServer name lookup populated from each helper's tools/list.
Restart-mutex layering arrives in Task 3.
- ToolMetadata struct: name + server + requiresConfirmation. Plan 05-04
/05-05 consume this for dispatch routing + confirmation broker.
- MockHelper fixture (test-only, internal to JarvisMCPTests): SDK Server
with mock_echo + mock_slow tools, MOCK_HELPER_CRASH_AFTER env knob to
exit(137) after N calls, MOCK_HELPER_TALLY_PATH side channel for
restart-cycle counting.
- MockHelperBuilder: shells out to `swift build -c release` once per test
run, caches the binary URL.
- Tests: 4 happy-path tests (echo round-trip, spawn-failed, helperMissing,
toolMetadata) + 3 source-level Pitfall #1 regression guards.
Plan: 05-01 Task 2 of 3.