Tulip Logo IconTulip
Concepts

MCP

Serve the tool catalog over MCP with Mcp.init, with the same permission checks as agents.

The MCP entrypoint exports Mcp, content helpers and shared types for turning tool output into model-readable content. It needs @modelcontextprotocol/server.

import { Mcp, json, resource, table, text } from "@tulip-systems/ai/mcp/server";

Mcp is independent of Agents and Chat: an app can serve its tools over MCP without agents, runs or chats.

Content helpers

  • text() for short human-readable results
  • json() for structured output
  • resource() for external or app resources
  • table() for row-based data

Set up the server

Mcp.init() takes the tools MCP apps can use and turns them into MCP tools. Each one checks the definition's permission for the request's user, like agents do, and formats the output with content (json(output) by default). Errors come back as an error result the client's model can read. Tools whose confirmation needs a proof, such as "passkey", are always refused: an MCP client cannot give one.

A tool with an outputSchema advertises it, and its result carries the output as structured content whatever content returns. content then only shapes the text, such as a table, for clients that read text.

import { aiMcpDrizzleAdapter } from "@tulip-systems/ai/drizzle";
import { Mcp, table } from "@tulip-systems/ai/mcp/server";
import { capabilities } from "@/server/ai/capabilities";

export const mcp = Mcp.init({
  tools: Object.values(capabilities),
  database: aiMcpDrizzleAdapter({ db, schema: { aiMcpAppSettings } }),
  content: {
    search_prospects: ({ output }) => table(output.prospects, { title: "Prospects" }),
  },
});

content is keyed by tool name, and its input and output are typed by that tool. The database stores what each user lets each app do. It is optional: without it every app has the default settings (tools without a confirmation are allowed, the others are not), and they cannot be changed.

Protect the route

MCP clients sign in with OAuth (Better Auth's OAuth provider) and send an access token. Verify it with createMcpProtectedRequestHandler() from @better-auth/mcp. It answers a missing or invalid token with a 401 that points the client to the protected-resource metadata, so the client can sign in on its own.

import { createMcpProtectedRequestHandler } from "@better-auth/mcp";
import { createDpopReplayStore } from "better-auth/oauth2";

export async function POST(request: Request) {
  const { internalAdapter } = await auth.$context;

  return createMcpProtectedRequestHandler(
    {
      issuer: OAUTH_ISSUER,
      audience: OAUTH_AUDIENCE,
      jwksUrl: OAUTH_JWKS_URI,
      challengeScopes: [...OAUTH_SCOPES],
      requiredScopes: ["mcp"],
      dpop: { replayStore: createDpopReplayStore(internalAdapter) },
    },
    async (req, jwt) => {
      // jwt.sub is the user, jwt.azp the OAuth client (the MCP app)
    },
  )(request);
}

Pass the issuer, audience and JWKS URL as constants. requireMcpAuth() reads them from the auth base URL, and fails before it can answer with a 401 when that URL is resolved per request.

requiredScopes: ["mcp"] refuses tokens issued for anything else, such as signing in with OpenID, with a 403 that names the missing scope.

Refuse banned users

Banning a user with Better Auth's admin plugin ends their sessions, but an access token stays valid until it expires. Load the user with their ban and refuse it:

if (user.banned && (!user.banExpires || user.banExpires > new Date())) {
  return new Response("The user is banned.", { status: 403 });
}

Know which app calls

The token's azp is the OAuth client: the app the user connected, such as Claude or Cursor. Look it up together with the user's consent. Access tokens stay valid until they expire, so this is what cuts off an app the user disconnected right away:

const [client] = await db
  .select({ id: oauthClients.clientId, name: oauthClients.name })
  .from(oauthClients)
  .innerJoin(oauthConsents, eq(oauthConsents.clientId, oauthClients.clientId))
  .where(and(eq(oauthClients.clientId, jwt.azp), eq(oauthConsents.userId, user.id)));

if (!client) {
  return new Response("The user revoked this client's access.", {
    status: 401,
    headers: {
      "WWW-Authenticate": `Bearer error="invalid_token", resource_metadata="${resourceMetadataUrl}"`,
    },
  });
}

Some clients share one client id across all their users, such as Claude Code with its client metadata document URL. Always key per-app settings on the user and the client together.

Serve the tools

Build the server for the access token's user and the app with mcp.server(). Every tool checks its permission for the user, like in the assistant, and only runs when the user allowed it for this app; an app the user turned off runs nothing. The tool base's context receives an mcp trigger with the app's clientId and clientName, so pass it as the actor's via and history shows which app made a change:

const server = await mcp.server({
  user,
  client: { id: client.id, name: client.name ?? "MCP client" },
  name: "my-app",
  version: "1.0.0",
});

const handler = createMcpHandler(() => server, { legacy: "reject" });

return handler.fetch(req);

mcp.server() registers every tool with its schemas and annotations, and passes the request's abort signal to the tool. Reads are marked read-only and deletes destructive (destructiveHint). The server has no approval step of its own: MCP clients ask their user before calling tools that are not read-only. Users choose what each of their apps may do with mcp.apps (see Mcp and Manage agents).

Guidance

  • Keep the canonical tool reusable.
  • Keep MCP descriptions clear and standalone.
  • Return compact content that is useful to a model.
  • Avoid leaking internal implementation details unless they are the point of the tool.

On this page