Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix(api): link a tool call's request to the one that reached /mcp (#810)

Croff69105b573dce
diff --git a/apps/api/src/mcp/__tests__/integration/client-request.test.ts b/apps/api/src/mcp/__tests__/integration/client-request.test.ts
new file mode 100644
index 00000000..f1476e2f
--- /dev/null
+++ b/apps/api/src/mcp/__tests__/integration/client-request.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { auth } from '@repo/auth';
+import { app } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { getMcpClientRequest } from '#shared/mcp-request';
+import { setRequestTracker } from '#shared/request-tracker';
+
+describe('a tool call over MCP', () => {
+ beforeEach(resetDb);
+ afterEach(() => setRequestTracker());
+
+ it('links the request it dispatches to the one that reached /mcp', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const { key } = await auth.api.createApiKey({ body: { userId: owner.userId, name: 'mcp' } });
+ const seen: { route: string; device: string | null | undefined }[] = [];
+ setRequestTracker(({ request, route }) => {
+ seen.push({ route, device: getMcpClientRequest(request)?.headers.get('user-agent') });
+ return undefined;
+ });
+
+ const answer = await app.handle(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${key}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ 'user-agent': 'mcp-client/1.0',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'list_projects', arguments: {} },
+ }),
+ }),
+ );
+ expect(await answer.text()).toContain('"ok":true');
+
+ expect(seen).toEqual([
+ { route: '/mcp', device: undefined },
+ { route: '/projects', device: 'mcp-client/1.0' },
+ ]);
+ });
+});
diff --git a/apps/api/src/mcp/dispatch.ts b/apps/api/src/mcp/dispatch.ts
index a7d3f10d..59666317 100644
--- a/apps/api/src/mcp/dispatch.ts
+++ b/apps/api/src/mcp/dispatch.ts
@@ -1,6 +1,11 @@
import type { McpApp } from './types';
import type { McpRouteTool } from './generate';
-import { AGENT_PROJECT_HEADER, MCP_LOOPBACK_HEADER, setMcpOAuthToken } from '../shared/mcp-request';
+import {
+ AGENT_PROJECT_HEADER,
+ MCP_LOOPBACK_HEADER,
+ setMcpClientRequest,
+ setMcpOAuthToken,
+} from '../shared/mcp-request';
import type { McpCredential } from './credential';
import { structuredResult, type StructuredResult } from './result';
import { withPublicAttachmentUrls, withStoredAttachmentUrls } from './attachment-urls';
@@ -24,12 +29,13 @@ const BASE = 'http://localhost';
// per-project MCP toggle. An internal agent run dispatches through the same routes
// but is not MCP, so disabling MCP on a project must not disarm its agents.
// projectId is the project an internal agent's run works in (AGENT_PROJECT_HEADER).
+// clientRequest is the request that reached POST /mcp (setMcpClientRequest).
export async function dispatchTool(
app: McpApp,
tool: McpRouteTool,
args: Record<string, unknown>,
credential: McpCredential,
- opts: { viaMcpEndpoint: boolean; projectId?: number },
+ opts: { viaMcpEndpoint: boolean; projectId?: number; clientRequest?: Request },
): Promise<{ text: string; isError: boolean; structuredContent: StructuredResult }> {
const rest = withStoredAttachmentUrls(args);
@@ -65,6 +71,7 @@ export async function dispatchTool(
body,
});
if (credential.kind === 'oauth') setMcpOAuthToken(request, credential.accessToken);
+ if (opts.clientRequest) setMcpClientRequest(request, opts.clientRequest);
const response = await app.handle(request);
const text = withPublicAttachmentUrls(await response.text());
return {
diff --git a/apps/api/src/mcp/mount.ts b/apps/api/src/mcp/mount.ts
index e78c9ee0..32948acf 100644
--- a/apps/api/src/mcp/mount.ts
+++ b/apps/api/src/mcp/mount.ts
@@ -31,7 +31,7 @@ export function mountMcp(app: any): void {
'/mcp',
async ({ request, body }: { request: Request; body: unknown }) => {
const serve = async (credential: McpCredential, userId: string) => {
- const server = await buildMcpServer(mcpApp, credential, userId);
+ const server = await buildMcpServer(mcpApp, credential, userId, request);
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
diff --git a/apps/api/src/mcp/server.ts b/apps/api/src/mcp/server.ts
index b3591a2f..3c7cb6d6 100644
--- a/apps/api/src/mcp/server.ts
+++ b/apps/api/src/mcp/server.ts
@@ -35,6 +35,7 @@ export async function buildMcpServer(
app: McpApp,
credential: McpCredential,
userId: string,
+ clientRequest?: Request,
): Promise<Server> {
const server = new Server(
// `name` is the stable programmatic identifier; `title` is the human-readable
@@ -91,6 +92,7 @@ export async function buildMcpServer(
}
const { text, isError, structuredContent } = await dispatchTool(app, tool, args, credential, {
viaMcpEndpoint: true,
+ clientRequest,
});
if (tool.images && !isError) return { content: imageContent(text) };
return { content: [{ type: 'text', text }], isError, structuredContent };
diff --git a/apps/api/src/shared/mcp-request.ts b/apps/api/src/shared/mcp-request.ts
index 14c09e0a..e14ddf68 100644
--- a/apps/api/src/shared/mcp-request.ts
+++ b/apps/api/src/shared/mcp-request.ts
@@ -13,6 +13,7 @@ export const MCP_LOOPBACK_HEADER = 'x-mcp-loopback';
export const AGENT_PROJECT_HEADER = 'x-agent-project';
const oauthTokens = new WeakMap<Request, string>();
+const clientRequests = new WeakMap<Request, Request>();
// True when the request came from an MCP tool dispatch.
export function isMcpRequest(headers: Headers): boolean {
@@ -32,3 +33,13 @@ export function setMcpOAuthToken(request: Request, token: string): void {
export function getMcpOAuthToken(request: Request): string | undefined {
return oauthTokens.get(request);
}
+
+// A dispatched request has no client address or device; the request that reached POST /mcp
+// has them. Like the OAuth token, this link is not in a header, so a client cannot set it.
+export function setMcpClientRequest(request: Request, client: Request): void {
+ clientRequests.set(request, client);
+}
+
+export function getMcpClientRequest(request: Request): Request | undefined {
+ return clientRequests.get(request);
+}