keystone-mcp
Mounts an MCP endpoint on a Keystone 6 app's Express server, exposing the schema's GraphQL queries and mutations as tools: searchTool discovers available operations with their arguments and selectable field paths, and callTool executes them (including mutations unless restricted with queriesOnly) as the user who signed in via OAuth password login, so Keystone's access control decides what the agent may read or change. Includes OAuth 2.1 authorization-server endpoints (dynamic client registration, PKCE code exchange, refresh, revocation), a configurable path/take limit, and project-specific server instructions.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
keystone-mcp
Mount an MCP endpoint on the Express server of a Keystone 6 app.
What the users of your app get
A user adds
https://<your app>/mcpto an MCP client, such as Claude Desktop, Claude Code or MCP Inspector. The client opens a page of your app, where the user signs in with their email and password and allows the client.The agent in the client gets two tools.
searchToolfinds the queries and mutations of the app, with their arguments and the field paths that a call can select.callToolruns one of them.The agent acts as the user who signed in. Keystone access control decides what it can read and change, as in the Admin UI: a user who may not update a post cannot update it through the agent either.
When it connects, the agent reads a short description of the project: your paragraph, then the kinds of records in plain words.
The package uses only the public hook server.extendExpressApp and the public context. It does not modify @keystone-6/core.
For a working app, start with the shop example in examples/shop: a small Keystone 6 shop with access rules, seed data, a storefront, and the steps to connect MCP Inspector and Claude Desktop.
Related MCP server: mcp-app-server
Install
npm install keystone-mcpThe app must have express and graphql installed; Keystone 6 brings both.
To try a local checkout instead, install it as a copy, so that the package shares the graphql and express copies of the app: npm install --install-links /path/to/keystone-mcp.
The package ships ESM (dist/index.js) and CommonJS (dist/cjs/index.js). Keystone compiles keystone.ts to CommonJS and loads the CommonJS build.
Wire it in keystone.ts
The package needs password sign-in from @keystone-6/auth (createAuth), because users sign in to the MCP endpoint with it. Without an authenticate<List>WithPassword mutation in the schema, keystoneMcp throws at start.
import { config } from '@keystone-6/core';
import { createAuth } from '@keystone-6/auth';
import { keystoneMcp } from 'keystone-mcp';
const { withAuth } = createAuth({ listKey: 'User', identityField: 'email', secretField: 'password' });
export default withAuth(
config({
db: { /* ... */ },
lists,
session,
server: {
extendExpressApp: keystoneMcp({
instructions: 'The blog of Example Inc. Authors write posts; readers leave comments.',
}),
},
}),
);To keep another extendExpressApp function, call both:
const mcp = keystoneMcp({ queriesOnly: true });
server: {
extendExpressApp: (app, context) => {
app.get('/health', (_req, res) => res.json({ ok: true }));
mcp(app, context);
},
},At start, and again after each keystone dev rebuild, the server log shows one line for the endpoint:
keystone-mcp: MCP endpoint at /mcp: 48 operations, search on, sign-in with authenticateUserWithPassword, sign-ins end at restart; keystoneMcp({ secret }) keeps them.It names the path, the number of operations that the agent can find, whether searchTool is on, the mutation that the sign-in page runs, and whether sign-ins survive a restart. When search is off, the line names the reason and the option that turns it on: search off (NODE_ENV=production); keystoneMcp({ introspection: true }) turns it on. With the secret option, the line ends with sign-ins sealed with secret.
Try it on your computer
An MCP client that runs on your computer, such as MCP Inspector or Claude Code, connects to http://localhost:3000/mcp directly. It needs no tunnel, no HTTPS and no trust proxy.
Start the app with a fixed session secret:
export SESSION_SECRET="$(openssl rand -hex 32)" npm run devkeystone.tsmust pass it to the session, for examplesession: statelessSessions({ secret: process.env.SESSION_SECRET }). Without a fixed secret, Keystone makes a new one each time it loadskeystone.ts, also at each dev rebuild, and the client must sign in again after each edit.Find the mount line in the log:
keystone-mcp: MCP endpoint at /mcp: … operations, search on, ….Connect a client.
MCP Inspector: run
npx @modelcontextprotocol/inspector. It opens its page in the browser. Click Add Servers, then + Add manually. Enter the server IDshop, choose the transportstreamable-http, enter the URLhttp://localhost:3000/mcp, and click Add. Then turn on the switch of theshopserver.Claude Code: run
claude mcp add --transport http shop http://localhost:3000/mcp.claude mcp listthen showsshopwith! Needs authentication. In Claude Code, run/mcp, chooseshop, and choose Authenticate.
The browser opens the sign-in page of the app. The page says where the browser goes next: the client's own address on your computer, for example
127.0.0.1:6274for MCP Inspector. Sign in as a user of the app, and click Sign in and allow.Run a call. In MCP Inspector, open Tools and choose
callTool. Enter the operationproductsand the select["name"], and click Execute Tool. The result holds the products that this user may read. In Claude Code, ask for the products.
After a schema edit, keystone dev rebuilds and logs the mount line again, with the new number of operations. The client stays signed in. After a restart of the process, it signs in again, unless the app sets secret.
Before you deploy
SESSION_SECRET. Set a random string of 32 characters or more, and pass it tostatelessSessions. Without it, each start makes a new secret, and every user signs in again. Give every process the same value.secret. Set a second random string of 32 characters or more, for exampleopenssl rand -hex 32inMCP_SECRET, and passkeystoneMcp({ secret: process.env.MCP_SECRET }). Give every process the same value. Then MCP clients stay signed in across a deploy or restart, and every process behind a load balancer accepts their tokens. Without it, clients and tokens live in the memory of one process: a restart signs every user out, and another process rejects them. A newsecretends every grant, so change it only to sign everyone out.trust proxy. Behind a proxy or tunnel that ends TLS, set Expresstrust proxyinextendExpressApp. Without it, Express reads each request ashttp, the OAuth URLs usehttp, and a client that connected overhttpsrefuses them. The server log warns once per process when a request hasX-Forwarded-Proto: httpsbut Express readshttp:keystone-mcp: a request to /.well-known/oauth-protected-resource/mcp has X-Forwarded-Proto: https, but Express reads it as http, so the OAuth URLs use http and MCP clients refuse them. Behind a proxy or tunnel that ends TLS, call app.set('trust proxy', 1) in extendExpressApp.const mcp = keystoneMcp(); server: { extendExpressApp: (app, context) => { app.set('trust proxy', 1); mcp(app, context); }, },introspection. WithNODE_ENV=production,searchToolis off by default, as in Apollo Server, and the mount line says so. To keep search, passkeystoneMcp({ introspection: true }).callToolworks either way.Several processes. Set
secretandSESSION_SECRETto the same values in each. Withoutsecret, run one process per app.
Connect Claude Desktop
Claude connects from Anthropic's cloud (160.79.104.0/21), so the app must be reachable over public HTTPS. For a local app, use a tunnel, for example cloudflared tunnel --url http://localhost:3000, and set trust proxy (see Before you deploy). To try the endpoint without a tunnel, use a local client: see Try it on your computer.
In Claude Desktop, open Customize > Connectors. On a Team or Enterprise plan, an Owner adds the connector in Organization settings > Connectors with Add, then Custom.
Click Add custom connector.
Enter a name, for example
Keystone, and the URL of the endpoint, for examplehttps://cms.example.com/mcp. The URL must be the app's public origin followed bypath.If the dialog asks how Claude identifies itself, choose Register automatically. The package supports dynamic client registration. Leave the OAuth client ID and secret empty.
Click Add, then Connect. A browser window opens the sign-in page of the app.
Check that the page says your browser goes to
claude.ai. Enter your Keystone email and password, and click Sign in and allow.The browser returns to Claude, and the connector shows as connected. Ask Claude, for example, "Find the posts with draft status and publish the first one."
Claude acts as the user who signed in. A user who may not update a post in the Admin UI cannot update it through Claude either.
Control what the agent can do
Keystone access control applies to each call. Two more levers exist in Keystone today.
Hide a list or an operation with graphql.omit. The catalog comes from the public GraphQL schema, so an operation that the schema omits is gone from searchTool and callTool, and from /api/graphql too:
Category: list({
access: allowAll,
// No deleteCategory and no deleteCategories, for any client.
graphql: { omit: { delete: true } },
fields: { /* ... */ },
}),Tell an MCP call from other calls with context.req. callTool runs with the context of the POST <path> request, so a hook sees context.req.url equal to path, for example /mcp. A request to /api/graphql has another url:
hooks: {
beforeOperation: ({ operation, context }) => {
if (context.req?.url === '/mcp') console.log(`An MCP client runs ${operation}.`);
},
},Options
Option | Default | Effect |
|
| The HTTP path of the endpoint. |
|
| When |
|
| The maximum |
|
| When |
| none | One paragraph about the project, in your words. The server instructions start with it, before the part that the package builds from the catalog. |
| none | A random string of 32 characters or more, the same in every process. With it, the OAuth clients, sign-ins, codes and tokens are sealed values that need no server state, so MCP clients stay signed in across a restart and every process accepts them. Without it, they live in the memory of the process and end at restart. A shorter string throws at start. See Sign-in for what a sealed grant cannot do. |
Behavior
POST <path>serves a stateless MCP Streamable HTTP endpoint with JSON responses. Each request creates a new MCP server.GET <path>andDELETE <path>respond405with JSON-RPC error code-32000.A
POST <path>without a valid access token gets401withWWW-Authenticate: Bearer … resource_metadata="<origin>/.well-known/oauth-protected-resource<path>".callToolrunscontext.withRequest(req, res)and thencontext.graphql.run, with the Keystone session of the user behind the access token. Keystone access control applies as for any GraphQL request.When a call fails,
callToolreturns a tool error whose text is{"errors":[{"message":…,"extensions":{"code":…}}]}with one of three codes.ACCESS_DENIED: Keystone denied access (KS_ACCESS_DENIED,KS_FILTER_DENIED).INVALID_INPUT: an argument has the wrong type, a validation failed, atakeexceeds the list's limit, or the catalog rejects the input (KS_USER_INPUT_ERROR,KS_VALIDATION_FAILURE,KS_LIMITS_EXCEEDED).SERVER_ERROR: every other failure, such as a database error (KS_PRISMA_ERROR), a hook that throws, an access function that does not return a boolean, or an unknown code. A list of field errors (KS_RELATIONSHIP_ERROR,KS_RESOLVER_ERROR,KS_EXTENSION_ERROR) getsACCESS_DENIEDorINVALID_INPUTonly when each of its field errors has that meaning.An
ACCESS_DENIEDorINVALID_INPUTerror keeps its message, because the message helps the agent fix the call; a wrong argument is named asArgument "take". ASERVER_ERRORgets a fixed sentence, and so does any message that names Keystone, GraphQL, Prisma or Apollo. When the agent gets a fixed sentence, the server logs the original error withconsole.error./api/graphqlkeeps Keystone's own codes and messages, and the app'sgraphql.apolloConfig.formatErrordoes not run on<path>.The
initializeresult carriesinstructionsfor the client: theinstructionsoption first, then the kinds of records in plain words (from the list names, for exampleproductsandorder lines), the operations for one record of each kind, and how to search and call. Withintrospectionoff, it still names the operations.The text that the agent reads (server instructions, tool and argument descriptions, the search-off message, the sign-in page, the session-ended errors and the errors of a failed call) describes the project and names no technology: no Keystone, GraphQL or Prisma.
The catalog skips the root field
keystone. Keystone builds a new catalog after each dev rebuild.The JSON and form body parsers run on
<path>and<path>/oauth/*only.
Sign-in (OAuth 2.1)
The package is the OAuth authorization server for its own endpoint. It serves:
Path | Purpose |
| Protected resource metadata (RFC 9728). |
| Authorization server metadata (RFC 8414). The issuer is the origin of the app. |
| Dynamic client registration (RFC 7591). Redirect URIs must use |
| The sign-in and consent page. It shows the host that the browser returns to. |
| Code exchange with S256 PKCE, and refresh. Each refresh returns a new refresh token. Without |
| Token revocation (RFC 7009). |
Redirect URIs match exactly. Only the port of a loopback redirect (
localhost,127.0.0.1,[::1]) can differ from the registered one.The sign-in page runs the app's password mutation. The client gets its own access token (1 hour) and refresh token; the Keystone session token is never readable by the client.
The grant ends with the Keystone session: when the session expires (
statelessSessionsmaxAge, 8 hours by default) or the user is deleted,/mcpanswers401and refresh answersinvalid_grant, so the client asks the user to sign in again.Without
secret, clients and tokens live in the memory of the process. They survive akeystone devrebuild, because Keystone keeps the package loaded. After a restart, each user signs in again. Run one process per app.With
secret, the server keeps no OAuth state. Theclient_id, the transaction of the sign-in page, the code and the tokens are values sealed with AES-256-GCM under a key derived fromsecret, so a client cannot read or change them. A value sealed with another secret, changed in one character, or expired gets401on/mcpand an error at the token endpoint. Aclient_idis about 250 characters and an access token about 900.What a sealed grant cannot do, because no server remembers its use: a code works more than once within its 5 minutes (PKCE still binds it to the client's verifier); a refresh token keeps working after it was used, until it expires (30 days), so its reuse is not detected; revoke does nothing, so a grant ends only when the Keystone session ends or the token expires; a sign-in page ends, and its limit of 5 password tries counts, only in the process that handled it, so another process accepts the same page until it expires (10 minutes). Keystone's
statelessSessionshas the same limits.The issuer and resource URLs come from each request:
req.protocoland theHostheader. Behind a proxy or tunnel that ends TLS, set Expresstrust proxy, so that the URLs usehttps. See Before you deploy.
Tool input
searchTool:
{ "text": "posts", "limit": 10 }callTool:
{
"operation": "posts",
"args": { "where": { "title": { "contains": "mcp" } }, "take": 5 },
"select": ["id", "title", "author.name"]
}Without select, callTool selects the top-level paths of the operation.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
One OAuth connector for your team's remote MCP servers, with Tool Packs, guardrails and logs.
Hosted MCP server with managed OAuth for 15+ toolkits: Google Workspace, Fitbit, Oura, Kalshi, etc.
Appreciate teammates, celebrate milestones, and run workspace ops from MCP clients via OAuth.
Hosted MCP for Google Workspace, Atlassian and Notion: one OAuth, per-user accounts, write access.
Related MCP Servers
AlicenseNot gradedqualityBmaintenanceEnables turning selected OpenAPI operations into authenticated MCP tools with branded OAuth, operation allowlisting, and live schema refreshes.Apache 2.0- AlicenseNot gradedqualityBmaintenanceEnables existing apps to expose their users and data to external AI agents via MCP with OAuth 2.1 authentication and scoped tools.51 npmMIT
- AlicenseNot gradedqualityCmaintenanceEnables any MCP client to read and edit database schemas (DBML/SQL), Mermaid diagrams, and shared board layouts, along with the organizations, projects, documents, and marketplace listings around them. It runs as a hosted OAuth 2.1 endpoint, so there is nothing to install and access is limited to what the signed-in user can already see.MIT
- AlicenseNot gradedqualityAmaintenanceEnables clients such as Claude, Cursor, VS Code, and Windsurf to manage workspaces, projects, tasks, and AI agents through a hosted OAuth endpoint or a local stdio package, and to generate MCP tools from OpenAPI specs.2,530 npmMIT