My In-App Agent Is Just Another MCP Client
While working on my personal garage software (the Garage App, my entry for the Symfony AI & MCP hackathon), I ended up with two kinds of agents calling the same tools. Claude Code, Claude Desktop or Goose connect to /mcp from the outside, and the app has its own agent behind /agent/turn that runs in a Messenger worker. In the previous post I looked at what the MCP server sends to the next API. This one is about the opposite direction: the in-app agent consumes the app’s own MCP server, in-process, with no HTTP and no OAuth.
Two consumers, one set of tools#
Every capability of the Garage App is an API Platform resource carrying both its HTTP operations and its MCP tools. For example, the parts for a service:
#[ApiResource(
mcp: [
'get_service_parts' => new McpTool(
title: 'Service Parts',
description: 'Get everything needed for a maintenance service on a vehicle in one call: ...',
input: ServicePartsInput::class,
structuredContent: false,
processor: ServicePartsProcessor::class,
annotations: ['readOnlyHint' => true, 'openWorldHint' => true],
),
],
)]
final class ServiceParts
{
}
Trimmed: the real description is a full paragraph written for the model.
API Platform generates the input schema from ServicePartsInput, validates the arguments, runs the processor and maps the result. External hosts see this through /mcp, behind the Casdoor firewall.
Now the in-app agent needs the same tools. Symfony AI’s way is #[AsTool] on a method, with a schema described from PHP types. I could have written a second set of #[AsTool] wrappers around the same processors, but then every tool has two descriptions, two schemas and two validation paths that will drift. And the description is the prompt: when I tune the wording for Claude Code, the in-app agent should get it too.
The other option is to call /mcp over HTTP from the worker. That means the worker needs a token to call itself, so either it holds the user’s bearer (the very thing the previous post removed from the queue) or it gets a service identity just to talk to its own process. Plus a network round-trip per tool call, through Caddy, to land in the same PHP code.
The MCP server is a service in the container though. The /mcp controller only feeds it a transport. So the agent can feed it another one.
The transport#
The first version (5c5035c, June) spoke the 2025-03-26 revision, where a request only makes sense inside a session opened by an initialize handshake. Each tool call ran two frames through a CapturingTransport: an initialize, then the actual request. Even that needed a custom transport, because the SDK’s InMemoryTransport discards responses, and the protocol layer does not hand sessioned responses to send() at all, it queues them on the session. So the transport drained the session’s outgoing queue after each frame, and its close() ended the throwaway session so the file session store would not grow with one session per tool call.
In November (9c71e5b) the agent moved to the 2026-07-28 revision, which is stateless: no initialize, every request carries its protocol version and client capabilities in _meta. The transport shrank to one request in, one response out:
final class InProcessTransport extends BaseTransport implements StatelessAwareTransportInterface
{
private ?StatelessProtocol $stateless = null;
public function __construct(private readonly array $request)
{
parent::__construct();
}
public function connectStateless(StatelessProtocol $protocol): void
{
$this->stateless = $protocol;
}
public function send(string $data, array $context): void
{
throw new LogicException('The in-process transport speaks the modern era only; nothing reaches the handshake dispatcher.');
}
public function listen(): array
{
if (null === $this->stateless) {
throw new LogicException('The MCP server was built without the modern era (mcp.servers.*.protocol_versions); the in-process agent needs it.');
}
$result = $this->stateless->handleInline(json_encode($this->request, \JSON_THROW_ON_ERROR));
if ($result->isEmpty() || $result->isStream()) {
return [];
}
return json_decode($result->toJson(), true, 512, \JSON_THROW_ON_ERROR);
}
}
Trimmed: docblocks, setHandshakeVersions() (a no-op) and a guard on the decoded type.
Like stdio, it has no header layer, so the request metadata travels inline (handleInline()). send() throws on purpose: only the legacy handshake path writes there, and the agent never takes it.
The toolbox#
McpToolbox implements Symfony AI’s ToolboxInterface and drives the server registered as mcp.server.garage, the one /mcp uses. Every request goes through drive(), which stamps the _meta envelope:
protected function drive(array $request): array
{
$request['params']['_meta'] = [
RequestMeta::PROTOCOL_VERSION => ProtocolVersion::V2026_07_28->value,
RequestMeta::CLIENT_CAPABILITIES => new \stdClass(),
RequestMeta::CLIENT_INFO => ['name' => 'in-process-agent', 'version' => '0.0.0'],
];
return $this->server->run(new InProcessTransport($request));
}
getTools() is a tools/list call whose definitions become Symfony AI Tool objects, name, description and inputSchema copied as the server advertises them:
$response = $this->drive(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list', 'params' => []]);
foreach ($definitions as $definition) {
if (\in_array($definition['name'], self::EXCLUDED, true)) {
continue;
}
$tools[] = new Tool(
new ExecutionReference(self::class, 'execute'),
$definition['name'],
$definition['description'] ?? '',
$definition['inputSchema'] ?? null,
);
}
Trimmed: the type guards on the decoded JSON, and the memoisation discussed below.
And execute() is a tools/call:
$response = $this->drive([
'jsonrpc' => '2.0',
'id' => 2,
'method' => 'tools/call',
'params' => [
'name' => $toolCall->getName(),
'arguments' => (object) $toolCall->getArguments(),
],
]);
The agent itself is configured in ai.yaml with tools: true, which gives it the bundle’s #[AsTool] toolbox. The bundle wires exactly one toolbox per agent, so a CompositeToolbox decorates ai.toolbox.garage and merges both families:
App\Mcp\Agent\McpToolbox:
arguments:
$server: '@mcp.server.garage'
App\Agent\Toolbox\CompositeToolbox:
decorates: ai.toolbox.garage
arguments:
$renderToolbox: '@.inner'
$mcpToolbox: '@App\Mcp\Agent\McpToolbox'
$narrator: '@App\Agent\Ui\StepNarrator'
A call whose name belongs to the MCP listing goes to McpToolbox, anything else to the #[AsTool] toolbox.
Is skipping OAuth a hole? No, the agent is a trusted in-process caller. The Casdoor gate on /mcp is a trust boundary for external hosts, while the worker only runs turns that /agent/turn already authenticated, and every garage read or write is still scoped to the owner of the turn.
The proof that it’s the same thing is a functional test, AgentMcpToolboxTest. It seeds a vehicle through the in-process bridge, calls list_vehicles both in-process and over real Streamable HTTP, and asserts the two payloads are identical:
$inProcess = $toolbox->execute(new ToolCall('1', 'list_vehicles', []))->getResult();
$sessionId = $this->initialize($client);
$http = $this->outcome($this->call($client, $sessionId, 'tools/call', [
'name' => 'list_vehicles',
'arguments' => [],
], 2));
$this->assertSame($http, $inProcess);
Another test listens to the SDK’s RequestEvent and pins that both tools/list and tools/call arrive with protocol version 2026-07-28.
Which tools the agent doesn’t get#
Not every MCP tool belongs to the agent. The Garage App also exposes render tools (select_vehicle, toast, show_fact, focus_view…) so that an external host like Claude Code can drive the 3D dashboard. Those publish to the owner’s pilot Mercure topic. The in-app agent has its own versions as #[AsTool] in RenderIntentTools, bound to the session topic of the browser tab that asked. Leaving the MCP twins visible would give the model two tools with the same name and send the frames to the wrong topic, so they sit in McpToolbox::EXCLUDED.
Note that this is a denylist, and that is the second version. The first one was an allowlist of 7 garage tools, to keep the agent’s context small. The next day 586b223 added update_vehicle and plan_maintenance to the server and the allowlist didn’t follow: the system prompt told the agent to call tools it could not see, so the usage write and the checklist silently did nothing. A denylist fails open, a new tool reaches the agent unless I explicitly hide it, and AgentMcpToolboxTest asserts the tools the prompt relies on are listed.
The Parts App (bonneref.fr) reuses the same pattern for its parts finder agent: an identical InProcessTransport, the same McpToolbox and CompositeToolbox. But there the toolbox takes an allowlist in its constructor (lookup_plate, decode_vin, list_makes, list_models, list_cars, get_service_parts, decode_build_code), because the finder is meant to see a fixed read-only subset and a tool added to the catalogue server later must not reach it unannounced. Same mechanism, opposite default, and the choice depends on what failing closed costs you.
What broke along the way#
A failed tool is not a missing tool#
The first execute() mapped any JSON-RPC error to ToolNotFoundException. When get_service_parts hit an upstream answering HTTP 401, the handler threw, the server answered INTERNAL_ERROR, and the model was told the catalogue tool did not exist. eec129b routes on the error code: only METHOD_NOT_FOUND stays a ToolNotFoundException, anything else becomes a ToolExecutionException, the type FaultTolerantToolbox turns into an error result the model can recover from. fault_tolerant_toolbox was off in the first version, so that CompositeToolbox was the only decorator, and went on the same day (337ed91): the bundle’s FaultTolerantToolbox now wraps CompositeToolbox from the outside.
A miss is a result, not a JSON-RPC error#
That was still not enough. Symfony AI’s ToolExecutionException::getToolCallResult() replaces the message with a fixed sentence, so a stalled plate registry and an unknown plate were the same string to the model, and it once told a user that a possibly valid plate did not exist. Domain errors became tool results carrying a status.
Then an upgrade quietly undid it. API Platform’s MCP handler catches HttpExceptionInterface around both the provider and the processor and returns an internal error with the raw message, so a NotFoundHttpException from a state processor never reached the error mapping and an unknown plate came back as -32603 again (6bf0831). The fix decorates only the MCP state provider and processor so that a miss is re-thrown as a plain RecordNotFoundException before API Platform inspects it. The REST surface still answers a 404.
Since 4bfbc4c the contract follows the tools error handling section of the spec: every failure is a result with isError: true and a <status>: <what to do> text, never a protocol error. On the agent side McpToolbox hands that result over as is:
if ($result['isError'] ?? false) {
return new ToolResult($toolCall, CallToolResult::fromArray($result));
}
The model reads isError next to the text, and RepeatedToolFailureGuard, which aborts a turn when the model keeps retrying the same failing call, counts it. The test for the 401 case now asserts the exact text the agent receives: upstream_rejected: the bonneref catalog rejected the request. Retrying will not help; check the arguments. This is where sharing the server pays off: the fix landed once, in the server, and both Claude Code and the in-app agent read the same status.
Never memoise an empty catalogue#
Messenger workers are long-lived, and both toolboxes cache the tool listing. If the in-process tools/list fails, the listing is empty, and caching [] strands the worker without tools until it restarts. McpToolbox::getTools() only memoises a non-empty list, and 6c7a9c6 fixed the same bug one level up: CompositeToolbox had cached an empty name map, routing every garage tool to the render toolbox for the life of the worker.
if ([] === $names) {
return false;
}
$this->mcpNames = $names;
The Garage App always exposes tools, so an empty answer is a transient failure, not a valid one. Leaving the cache empty lets the next turn re-fetch.
The principle#
If your app already has an MCP server, its own agent should be one more client of it, in-process, so there is one definition of what a tool is and one way it fails!