branben/OmniRoute · Pull Request #15983

How the MCP v2 sidecar handles a request

feat/mcp-v2-sidecar → release/v3.8.53 school-core-hr6

OmniRoute's MCP surface now has two parallel servers. The v1 server is untouched — 37 tools over stdio, HTTP (SSE), and streamable HTTP, still rejecting the 2026-07-28 header with 400. The new v2 sidecar lives under open-sse/mcp-server/v2/, speaks the 2026-07-28 wire format, and is opt-in behind the OMNIROUTE_MCP_V2 feature flag. A modern client sends MCP-Protocol-Version: 2026-07-28 and gets server/discover, resultType, cacheable lists, _meta, and 8 tools calling omniRouteFetch() against real OmniRoute endpoints. A legacy client sees v1 unchanged.

Open module graph ↗ Interactive architecture diagram of the v2 sidecar.

Callstack walkthrough

1 src/app/api/mcp/v2/route.ts :20-48

A request arrives at /api/mcp/v2. The route imports handleMcpV2Http and isMcpV2Enabled from the v2 server module. Before any protocol work happens, guardEnabled() checks settings.mcpEnabled and then isMcpV2Enabled() — if either is off, the route returns 503 with a clear message. Only after both gates pass does the route call requireManagementAuth(request, { acceptMcpConnectScope: true }).

import { isMcpV2Enabled, handleMcpV2Http } from "@omniroute/open-sse/mcp-server/v2/server";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";

export async function POST(request: Request) {
  const authError = await requireManagementAuth(request, { acceptMcpConnectScope: true });
  if (authError) return authError;
  const blocked = await guardEnabled();
  if (blocked) return blocked;
  return handleMcpV2Http(request);
}
2 src/shared/constants/featureFlagDefinitions.ts :534-542

The OMNIROUTE_MCP_V2 flag is registered at slot 85 with defaultValue: "false", type: "boolean", and warningLevel: "caution". It is read at module load time, not per-request, so an operator's toggle takes effect on the next process start — the same pattern as OMNIROUTE_MCP_ENFORCE_SCOPES. This means v2 stays closed unless an operator explicitly opens it; legacy traffic is unaffected.

{
  key: "OMNIROUTE_MCP_V2",
  label: "MCP v2 Sidecar",
  description:
    "Enable the experimental 2026-07-28 spec MCP v2 sidecar (stateless, no handshake). Off by default; v1 is untouched.",
  defaultValue: "false",
  type: "boolean",
  requiresRestart: true,
  warningLevel: "caution",
}
3 open-sse/mcp-server/v2/server.ts :144-163

handleMcpV2Http creates a fresh v2 server per request (D7). Before any tool runs, withScopeEnforcement wraps each handler. It calls resolveCallerScopeContext with only { authInfo, sessionId } — the client's _meta is never consulted for scope grants (D4). If the check fails, buildScopeDenialMessage strips caller-influenced fields like Caller= and source= from the client-facing surface (D5).

function withScopeEnforcement(
  toolName: string,
  handler: (args: unknown, extra?: McpToolExtraLike) => Promise,
  toolScopes?: readonly string[]
) {
  return async (args: unknown, extra?: McpToolExtraLike): Promise => {
    const scopeContext = resolveCallerScopeContext(
      { authInfo: extra?.authInfo, sessionId: extra?.sessionId },
      Array.from(MCP_ALLOWED_SCOPES)
    );
    const scopeCheck = evaluateToolScopes(
      toolName, scopeContext.scopes, isMcpScopeEnforcementEnabled(), toolScopes
    );
    if (!scopeCheck.allowed) {
      const msg = buildScopeDenialMessage(toolName, scopeCheck.missing);
      // callerId stays in audit payload only — never echoed to client
      await logToolCall(toolName, args, null, 0, false, msg);
      return { content: [{ type: "text", text: msg }], isError: true };
    }
    return handler(args, extra);
  };
}
4 open-sse/mcp-server/v2/server.ts :394-412

createMcpServerV2() builds the server and registers all 8 tools from the V2_TOOLS array. Each tool is wrapped in withScopeEnforcement at registration time. The tool definitions include outputSchema where applicable — this is the v2 addition; v1 omitted it entirely. Every tool calls omniRouteFetch() against real OmniRoute endpoints, not mocks.

export function createMcpServerV2(): McpServerV2 {
  const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
  for (const tool of V2_TOOLS) {
    server.registerTool(
      tool.name,
      {
        description: tool.description,
        inputSchema: tool.inputSchema,
        ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
      },
      withScopeEnforcement(tool.name, tool.handler, tool.scopes)
    );
  }
  return server;
}
5 open-sse/mcp-server/v2/server.ts :442-449

The server/discover handler replaces the v1 initialize handshake. It is registered as a real request handler over any transport (stdio or the stateless HTTP route). The response is honest: capabilities.tools only — no unregistered resources or prompts. This is the mechanism that lets a 2026-07-28 client learn the v2 surface without a session.

// server/discover is a REAL request handler, not a stub.
server.server.setRequestHandler(
  z.object({ method: z.literal("server/discover"), params: z.any().optional() }),
  async () => buildDiscoverResult(V2_TOOLS.length)
);

export function buildDiscoverResult(toolCount: number): DiscoverResult {
  return {
    name: SERVER_NAME,
    version: SERVER_VERSION,
    protocolVersion: PROTOCOL_VERSION,
    capabilities: { tools: { listChanged: true } },
    toolsCount,
    features: ["tools/list", "tools/call", "server/discover"],
  };
}
6 open-sse/mcp-server/v2/server.ts :322-340

The V2_TOOLS array defines exactly 8 tools. Each entry spreads the base tool definition and adds outputSchema, cacheTtlMs, and scope requirements. All 8 call omniRouteFetch() against real OmniRoute endpoints — health, combos, metrics, switch, quota, providers, models, and router status. This is a bounded, reviewable surface, not a full catalog migration.

const V2_TOOLS: V2ToolDefinition[] = [
  { ...getHealthTool, outputSchema: getHealthOutput, cacheTtlMs: CACHE_TTL.health },
  { ...listCombosTool, outputSchema: listCombosOutput, cacheTtlMs: CACHE_TTL.combos },
  { ...getComboMetricsTool, outputSchema: getComboMetricsOutput },
  { ...switchComboTool, outputSchema: switchComboOutput },
  { ...checkQuotaTool, outputSchema: checkQuotaOutput },
  { ...listProvidersTool, outputSchema: listProvidersOutput },
  { ...listModelsTool, outputSchema: listModelsOutput },
  { ...getRouterStatusTool, outputSchema: getRouterStatusOutput },
];