Documentation menuMenu da documentação

$ cat docs/recipes/mcp.md

Recipe: MCP for agentsReceita: MCP para agentes

Give an AI agent a few routes of your API. It gets the same access rules as any client and no health data unless you release it.Dê a um agente de IA algumas rotas da sua API. Ele recebe as mesmas regras de acesso de qualquer cliente e nenhum dado de saúde, a menos que você libere.

1. Pick the routes1. Escolher as rotas

Mark the routes the agent may call with tags: ['mcp']. Everything else stays invisible. Prefer read routes: GET is marked read only, while PUT, PATCH and DELETE carry the destructive hint.

Marque as rotas que o agente pode chamar com tags: ['mcp']. O resto fica invisível. Prefira rotas de leitura: GET sai marcada como somente leitura, enquanto PUT, PATCH e DELETE levam a dica de destrutiva.

2. Classify what is sensitive2. Classificar o que é sensível

Classify the response schema. By default pii and health fields are removed from the tool result and listed in _meta['tupik/removed']. allowDataClasses: ['pii'] releases names and e-mails here; the diagnosis stays out. secret never goes.

Classifique o schema de resposta. Por padrão os campos pii e health saem do resultado da ferramenta e ficam listados em _meta['tupik/removed']. Aqui o allowDataClasses: ['pii'] libera nome e e-mail; o diagnóstico fica fora. secret nunca vai.

3. Mount the server3. Montar o servidor

Serve mcp.fetch on /mcp next to the app. allowedOrigins lists the browser origins that may call it; requests without Origin (server agents) pass.

Sirva o mcp.fetch em /mcp ao lado do app. O allowedOrigins lista as origens de navegador que podem chamar; pedidos sem Origin (agentes em servidor) passam.

worker.ts
import { classify, createApp, createModule } from '@tupik/core';
import { createMcpServer } from '@tupik/mcp';
import { z } from 'zod';
import { auth, db } from './services';

type Doctor = { id: string };
declare module '@tupik/core' {
  interface TupikRegister {
    principal: Doctor;
  }
}

const Patient = classify(
  z.object({ id: z.string(), name: z.string(), email: z.string(), diagnosis: z.string() }),
  { email: 'pii', diagnosis: 'health' },
);

const clinic = createModule()
  .get('/patients/:id', {
    access: { owner: async (ctx) => (await db.patient(ctx.params.id))?.doctorId },
    tags: ['mcp'], // opt-in: only tagged routes become tools
    schema: { params: z.object({ id: z.string() }), response: { 200: Patient } },
    handler: (ctx) => db.patient(ctx.params.id),
  })
  .get('/appointments', {
    access: 'authenticated',
    tags: ['mcp'],
    handler: (ctx) => db.appointments(ctx.principal.id),
  })
  .delete('/patients/:id', {
    // no tag: agents never see this route
    access: (ctx) => ctx.principal.id === 'admin',
    handler: (ctx) => ctx.status(204).text(''),
  });

const app = createApp({ authenticate: (ctx) => auth.doctorFromBearer(ctx.req.headers.get('authorization')) }).register(clinic);

const mcp = createMcpServer(app, {
  name: 'clinic',
  version: '1.0.0',
  instructions: 'Read appointments and patient records of the signed-in doctor.',
  allowDataClasses: ['pii'], // names and e-mails may go; diagnosis stays out
  allowedOrigins: ['https://agent.example.com'],
});

export default {
  fetch: (request: Request) => (new URL(request.url).pathname === '/mcp' ? mcp.fetch(request) : app.fetch(request)),
};
import { classify, createApp, createModule } from '@tupik/core';
import { createMcpServer } from '@tupik/mcp';
import { z } from 'zod';
import { auth, db } from './services';

type Doctor = { id: string };
declare module '@tupik/core' {
  interface TupikRegister {
    principal: Doctor;
  }
}

const Patient = classify(
  z.object({ id: z.string(), name: z.string(), email: z.string(), diagnosis: z.string() }),
  { email: 'pii', diagnosis: 'health' },
);

const clinic = createModule()
  .get('/patients/:id', {
    access: { owner: async (ctx) => (await db.patient(ctx.params.id))?.doctorId },
    tags: ['mcp'], // opt-in: só rotas marcadas viram ferramentas
    schema: { params: z.object({ id: z.string() }), response: { 200: Patient } },
    handler: (ctx) => db.patient(ctx.params.id),
  })
  .get('/appointments', {
    access: 'authenticated',
    tags: ['mcp'],
    handler: (ctx) => db.appointments(ctx.principal.id),
  })
  .delete('/patients/:id', {
    // sem marca: agentes nunca veem esta rota
    access: (ctx) => ctx.principal.id === 'admin',
    handler: (ctx) => ctx.status(204).text(''),
  });

const app = createApp({ authenticate: (ctx) => auth.doctorFromBearer(ctx.req.headers.get('authorization')) }).register(clinic);

const mcp = createMcpServer(app, {
  name: 'clinic',
  version: '1.0.0',
  instructions: 'Read appointments and patient records of the signed-in doctor.',
  allowDataClasses: ['pii'], // nome e e-mail podem ir; diagnóstico fica fora
  allowedOrigins: ['https://agent.example.com'],
});

export default {
  fetch: (request: Request) => (new URL(request.url).pathname === '/mcp' ? mcp.fetch(request) : app.fetch(request)),
};

4. Call a tool4. Chamar uma ferramenta

The tool name is the route's operation id. The call becomes GET /patients/p1 with the authorization header of the MCP request. Without a token the result is UNAUTHORIZED; for a patient of another doctor it is NOT_FOUND.

O nome da ferramenta é o operation id da rota. A chamada vira GET /patients/p1 com o header authorization do pedido MCP. Sem token o resultado é UNAUTHORIZED; para paciente de outro médico é NOT_FOUND.

request.http
POST /mcp
authorization: Bearer <doctor token>
content-type: application/json

{ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
  "params": { "name": "getPatientsById", "arguments": { "params": { "id": "p1" } } } }

What can go wrongO que pode dar errado

  • An unclassified field goes to the model. Run tupik audit to list routes that return personal data, and classify before tagging.
  • A token with wide scopes gives the agent wide access. Issue agent tokens with the smallest scope, for example with apiKey scopes.
  • Batches, GET streams and sessions are not offered. Clients that need them get an error or 405.
  • Campo sem classe vai para o modelo. Rode o tupik audit para listar as rotas que devolvem dado pessoal, e classifique antes de marcar.
  • Token com escopo largo dá acesso largo ao agente. Emita tokens de agente com o menor escopo, por exemplo com os escopos do apiKey.
  • Lotes, streams por GET e sessões não são oferecidos. Clientes que precisam disso recebem erro ou 405.

Full option list: MCP server.

Lista completa de opções: Servidor MCP.