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.

3.4 KB
Raw Blame
import type { McpApp } from './types';
import type { McpRouteTool } from './generate';
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';

// Methods that carry a request body; the rest put their arguments in the query.

// Elysia's router needs a multi-label host to parse the path; a single-label host
// like "http://x" fails to route. localhost is never resolved (app.handle runs in
// process), so it is only a syntactically valid base for the URL.
const BASE = 'http://localhost';

// Runs a tool call as an in-process request against the real route and returns the
// response body as text. Path params fill the URL; the remaining arguments become
// the JSON body (POST/PUT/PATCH) or the query string (GET/DELETE). The caller's API
// credential is forwarded to the route session guard so permission checks run
// exactly as they do over HTTP.
//
// viaMcpEndpoint says whether the call came from POST /mcp. It is explicit at both
// call sites because it selects a real behaviour: only an MCP call carries the
// loopback header, and only a request carrying that header is subject to the
// 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; clientRequest?: Request },
): Promise<{ text: string; isError: boolean; structuredContent: StructuredResult }> {
  const rest = withStoredAttachmentUrls(args);

  let path = tool.path;
  for (const name of tool.pathParams) {
    path = path.replace(`:${name}`, encodeURIComponent(String(rest[name] ?? '')));
    delete rest[name];
  }

  const hasBody = tool.hasBody;
  let url = `${BASE}${path}`;
  let body: string | undefined;
  if (hasBody) {
    body = JSON.stringify(rest);
  } else {
    const qs = new URLSearchParams();
    for (const [key, value] of Object.entries(rest)) {
      if (value != null) qs.set(key, String(value));
    }
    const query = qs.toString();
    if (query) url += `?${query}`;
  }

  const request = new Request(url, {
    method: tool.method,
    headers: {
      'content-type': 'application/json',
      ...(credential.kind === 'api-key' ? { 'x-api-key': credential.apiKey } : {}),
      // Marks this as an MCP call so guards enforce the per-project MCP toggle.
      ...(opts.viaMcpEndpoint ? { [MCP_LOOPBACK_HEADER]: '1' } : {}),
      ...(opts.projectId != null ? { [AGENT_PROJECT_HEADER]: String(opts.projectId) } : {}),
    },
    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 {
    text,
    isError: response.status >= 400,
    structuredContent: structuredResult(response, text, tool.method, tool.outputSchema),
  };
}