Execution Router¶
Feature spec for code-forge implementation planning. Source: extracted from apcore-mcp/docs/tech-design-apcore-mcp.md Created: 2026-04-06
Purpose¶
The Execution Router is the central dispatcher that receives tool-call requests from the MCP server and routes them through apcore's Executor pipeline. It ensures that every tool call from an AI agent is subject to the same rigorous validation, security (ACL), and middleware rules as any other module invocation in the apcore ecosystem.
Scope¶
Included:
- Routing tool calls by module_id with incoming arguments (dict).
- Integration with apcore's Executor.call_async() to handle both sync and async modules.
- Serialization of module output (from dicts) into standard JSON strings for MCP TextContent.
- Redaction of sensitive fields in tool output before returning to the agent.
- Optional capturing of pipeline traces for observability.
- Pre-execution validation ("Preflight Check") to verify if a tool call would succeed.
Excluded:
- Direct module execution (always delegates to Executor).
- Protocol-level message handling (handled by the MCP SDK).
Core Responsibilities¶
- Dispatcher — Maps the tool name to the appropriate apcore
module_idand executes it through the full 11-step pipeline. - Output Normalization — Converts various module output types into a consistent JSON string format using
json.dumps()with adefault=strfallback for non-serializable objects. - Data Protection — Automatically redacts fields marked as sensitive (
x-sensitive: true) and keys matching_secret_*to prevent accidental leak of credentials to AI agents. - Validation Gateway — Provides a non-destructive preflight validation path (
Executor.validate()) that checks ACLs and schemas without executing the actual module.
Interfaces¶
Inputs¶
- Tool Name (MCP Client) — The identifier of the tool to be called (maps to
module_id). - Arguments (MCP Client) — A dictionary of input values conforming to the tool's
input_schema.
Outputs¶
- CallToolResult (MCP SDK) — The final result (success with text content or error).
- PreflightResult (Internal/Explorer) — A summary of check results (module lookup, ACL, schema validation) without execution.
Dependencies¶
- apcore SDK (language-equivalent: apcore-python / apcore-js / apcore Rust crate) — Provides the
Executor,Context, andRegistry. - Error Mapper — Used to transform execution failures into formatted MCP error responses.
Data Flow¶
graph TD
A[MCP Tool Call] --> B[Execution Router]
B --> C{Preflight Check?}
C -- Yes --> D[Executor.validate]
C -- No --> E[Executor.call_async]
E --> F[Full 11-Step Pipeline]
F --> G[Module Output]
G --> H[Redact Sensitive Fields]
H --> I[JSON Serialize]
I --> J[CallToolResult Output]
Key Behaviors¶
Full Pipeline Enforcement¶
The router ensures every call passes through all 11 apcore pipeline steps: context creation, call-chain guard, module lookup, ACL check, approval gate, middleware before, input validation, execution, output validation, middleware after, and final return.
ExtensionManager Plugin Points¶
When the server is constructed with an ExtensionManager (see ./extension-bridge.md and apcore/docs/features/extension-system.md), the router itself does not register extensions — ExtensionManager.apply() runs during factory setup and mutates the underlying Executor and Registry. Three pipeline steps are the effective observation/mutation sites for extension-driven behavior:
- Step 2 (module lookup) — observes the
discovererandmodule_validatorextension points, wired onto theRegistrybefore the router is constructed. - Step 5 (middleware before) / Step 10 (middleware after) — observe user-registered
middlewareextensions layered onto theExecutor, including theTracingMiddlewarefed byspan_exporterextensions. Theaclandapproval_handlerextensions take effect at Steps 4 and 5 respectively via their dedicated executor slots.
The router's contract with extensions is strictly pass-through: it forwards the current Context and arguments into the Executor and never skips pipeline steps, so registered extensions always fire exactly once per tool call.
Output Redaction¶
The pending core dependency fixes must honor x-sensitive through local schema
references, including nested arrays, composition branches and recursive data.
The MCP bridge uses the core redactor; it must not duplicate reference-redaction
logic in the adapter. Validate the resulting redacted object against the exact
advertised output schema before publishing structured results.
Before the output is sent to the AI agent, the router applies recursive redaction. Any field with x-sensitive: true in its schema or any key starting with _secret_ has its value replaced by "***REDACTED***".
Async-First Strategy¶
The router always uses Executor.call_async(). This allows the MCP server to remain responsive by offloading synchronous module executions to worker threads via asyncio.to_thread() automatically.
Constraints¶
- Thread Safety: Must handle concurrent tool calls from multiple clients safely.
- Latency: The routing layer itself should add minimal overhead (< 5ms) beyond the actual module execution time.
- Data Integrity: Must operate on a deep copy of the output if redaction or transformation is required.
Error Handling¶
- Dispatch Failures: Catches all execution errors (ModuleNotFoundError, ACLDeniedError, etc.) and routes them to the
ErrorMapperto prevent raw tracebacks from reaching the client. - Serialization Failures: Provides a safe fallback if the module output cannot be converted to JSON.
Version Hint Negotiation¶
The Execution Router resolves an optional version_hint (semver range) for every tool call and forwards it to Executor.call(..., version_hint=...) so that apcore can pin module version resolution. The hint is cross-language and travels on the wire as MCP request metadata.
Wire Contract¶
The MCP client carries the hint at params._meta.apcore.version (string). Example:
{
"method": "tools/call",
"params": {
"name": "my-module",
"arguments": { "...": "..." },
"_meta": { "apcore": { "version": ">=1.2.0" } }
}
}
Value Format¶
- Semver range string (e.g.,
">=1.0.0","1.2.x","^2.0"). - Maximum length: 64 characters.
- Allowed charset:
[A-Za-z0-9.\-+_~^>=<* ].
Precedence Order¶
When multiple sources supply a hint, the router resolves in this order (first match wins):
1. Explicit extras.version_hint / extra.versionHint — SDK caller-supplied (highest priority).
2. MCP request _meta.apcore.version — client-supplied.
3. Module descriptor default metadata.version_hint / metadata.versionHint (lowest).
4. None — no pinning; apcore resolves to the latest matching version.
Validation¶
- Values exceeding the length cap or containing characters outside the allowed charset are silently dropped (treated as absent), with a
debug-level log line for diagnosis. - Malformed semver ranges are passed through to apcore unchanged; apcore rejects them with the standard
invalid_version_rangeerror, which is surfaced via the Error Mapper. - The
_metadict is untrusted input from the MCP client; SDKs MUST bound-check and charset-validate before forwarding to the Executor (security note).
Trace-Mode Caveat¶
When the request carries _meta.trace == true, version_hint may be unavailable in some SDKs pending apcore 0.19's call_with_trace signature extension. This is a known gap tracked by the Rust SDK TODO (src/server/router.rs, see TODO(apcore>=0.19)); implementations that cannot forward the hint through the trace path MUST still honor it on the non-trace path.
Implementation References¶
- Python:
src/apcore_mcp/server/router.py(version_hint extraction around the_meta.apcore.versionbranch). - TypeScript:
src/server/router.ts(versionHintresolution at the extras/_meta.apcore.version/descriptor cascade). - Rust:
src/server/router.rs(handle_call—version_hintextraction andTODO(apcore>=0.19)streaming-trace gap).
Cancellation Handling¶
In-flight tool calls¶
Python, TypeScript, and Rust forward MCP request cancellation
to the APCore CancelToken for the in-flight tools/call on stdio and
initialized Streamable HTTP sessions. The transport resolves
params.requestId within the connection or HTTP session that sent the
notification. Other calls in that session and calls with the same request ID
in other sessions continue.
| SDK | How the notification reaches the module |
|---|---|
| Python | The MCP SDK cancels the request coroutine. The factory flips the invocation token before cancelling and awaiting the router task. |
| TypeScript | The MCP SDK aborts the request signal. The router's abort listener flips the invocation token. |
| Rust | The transport flips the request-scoped token. Its child token is attached to the module's execution context. |
Modules can poll the token in synchronous work or check it at asynchronous work boundaries. Cancellation is cooperative. A module that starts a subprocess or acquires a resource must stop that work and release the resource when it observes cancellation or otherwise unwinds. Clients should discard any response that races with their cancellation notification.
Programmatic calls and background tasks¶
Programmatic callers use ExecutionRouter.cancel(call_id, reason) in Python
and TypeScript or ExecutionRouter::cancel_call in Rust. These APIs take the
router's call ID. If a module raises ExecutionCancelledError and the router
returns an error result, the Error Mapper uses EXECUTION_CANCELLED.
APCore background tasks have their own lifecycle. Cancel a submitted task
with __apcore_task_cancel and its task_id. Session teardown has a
separate background-task hook.
Notes¶
- This component is the primary security boundary between the untrusted AI agent and the internal apcore module environment.
- It leverages the
ContextVarsystem to preserve identity and tracing across async boundaries.
Contract: ExecutionRouter.handle_call¶
Inputs¶
- tool_name: str, required, validates[non-empty], reject_with=(error content, is_error=True, None)
- arguments: dict[str, Any], required, validates[dict type]
- extra: dict[str, Any] | None, optional — may contain:
progress_token,send_notification,session,identity,call_id,_meta,version_hint
Errors¶
- Returns
(content, is_error=True, trace_id)with ErrorMapper output — for all execution exceptions (ModuleNotFoundError, ACLDeniedError, etc.) - Returns
(content, is_error=True, None)with validation message — whenvalidate_inputs=Trueand schema fails - The router converts execution exceptions to error tuples. Transport-level request cancellation can interrupt the call.
Returns¶
- On success: tuple
(content: list[dict], is_error: bool, trace_id: str|None) contentis a list of{"type": "text", "text": str}dictsis_error: Falseon success,Trueon any execution failuretrace_idiscontext.trace_idwhen context is available, else None- Version hint 3-source cascade: 1)
extra.version_hint, 2)extra._meta.apcore.version, 3)descriptor.metadata.version_hint; first non-None wins; passed toExecutor.call_async(version_hint=...)
Properties¶
- async: true
- thread_safe: true
- pure: false
- idempotent: false
Contract: ExecutionRouter constructor¶
Per-language idiom — there is no from_executor factory; the router is constructed directly:
- Python: ExecutionRouter.__init__(executor, *, validate_inputs=False, output_formatter=None, redact_output=True, output_schema_map=None, trace=False, async_bridge=None, descriptor_lookup=None) — invoked as ExecutionRouter(executor, ...).
- TypeScript: new ExecutionRouter(executor: Executor, options?: ExecutionRouterOptions) where options carries { validateInputs?, outputFormatter?, redactOutput?, trace?, outputSchemaMap?, asyncTaskBridge?, descriptorLookup? } (camelCase).
- Rust: ExecutionRouter::new(executor: Box<dyn Executor>, validate_inputs: bool, output_formatter: Option<OutputFormatter>) -> Self, with optional builder-style configuration via with_tool_schemas(...), with_output_schemas(...), with_redact_output(bool), with_trace(bool), and with_async_bridge(Arc<AsyncTaskBridge>). A no-arg ExecutionRouter::stub() -> Self is also provided for tests, plus a new_with_formatter(executor, validate_inputs, output_formatter) convenience.
Inputs¶
- executor: Any, required (duck-typed in Python/TS;
Box<dyn Executor>in Rust) — must expose asynccall_async(module_id, inputs, context?)method (Python/TS) or implement theExecutortrait (Rust) - validate_inputs / validateInputs: bool, optional, default=false
- output_formatter / outputFormatter: callable | None, optional
- redact_output / redactOutput: bool, optional, default=true in all three. Rust sets it in its constructors (
router.rs:473,497,524) and exposeswith_redact_output(bool)to turn it off; an earlier revision of this spec said Rust defaulted to false, which would have made Rust the one bridge that leakedx-sensitiveoutput by default. - output_schema_map / outputSchemaMap: dict | None, optional (Rust uses
with_output_schemas(...)) - trace: bool, optional, default=false
- async_bridge / asyncTaskBridge: AsyncTaskBridge | None, optional (Rust accepts
Arc<AsyncTaskBridge>viawith_async_bridge(...)) - descriptor_lookup / descriptorLookup: callable | None, optional (Python/TS only; Rust resolves descriptors via
with_tool_schemas)
Errors¶
- No constructor errors (fail-late at call time)
Returns¶
- On success: ExecutionRouter instance
Properties¶
- async: false
- thread_safe: true
- pure: false
- idempotent: true