Backend integration guide
Add an MCP endpoint to your SaaS with Express
Put an MCP endpoint in front of an existing authorized application operation when external agents need to discover and call it without an open browser tab. Keep identity, tenant checks and business rules in your service; MCP is the interface, not a replacement for authorization.
This walkthrough runs a read-only invoice lookup locally, including real HTTP authorization failures. No model, model API key, Bunkhouse account or private download is needed.
Run the example · Check access boundaries · Plan production OAuth
Choose a backend endpoint only when that is the job
- Known integration, known operations: a documented API may already be enough. Do not add MCP solely to rename an HTTP route.
- Compatible agents need tool discovery and service data: wrap your existing data layer in a service-hosted MCP endpoint. The client supplies the agent/model; this server does not run an agent loop or schedule jobs.
- A user needs help inside your existing page: an in-app assistant may fit better. Bunkhouse combines page/API skill discovery, an Assistant pane, sandboxed execution and classified-action review. It is not an unattended backend executor.
The MCP, WebMCP and live-tab comparison explains the execution choices. For an app-owned model loop instead of an external tool server, use the Express agent guide.
1. Create a disposable local project
Use Node.js 24 and npm, with port 3000 free. The commands pin the SDK packages used here: server 2.4.0, Express adapter 2.0.2 and Node adapter 2.1.2. They use the SDK's per-request HTTP factory, not the v1 transport constructor. This example accepts protocol revision 2026-07-28 only; it is not a compatibility claim for any named client or for Bunkhouse's separate relay.
Local credentials only. The random key signs five-minute test tokens for two dummy users. Keep it in this disposable directory, out of source control and browser code. Anyone with the key can mint these local tokens. Do not reuse it or expose this server publicly. No OAuth authorization server runs at the example issuer on port 3001; the checks mint tokens directly, so this does not test an OAuth login.
mkdir saas-mcp-local
cd saas-mcp-local
npm init -y
npm pkg set type=module
npm install --save-exact @modelcontextprotocol/server@2.4.0 @modelcontextprotocol/express@2.0.2 @modelcontextprotocol/node@2.1.2 express@5.3.0 jose@6.2.17 zod@4.6.7 tsx@4.23.15
node -e "require('node:fs').writeFileSync('.local-key',require('node:crypto').randomBytes(32),{mode:0o600,flag:'wx'})"The key creation refuses to overwrite an existing key. If restarting the same project, keep its current key and skip that command. For optional strict TypeScript checking, install typescript@7.0.2 @types/node@26.6.6 @types/express@5.0.6 as dev dependencies.
2. Verify the caller, then read an authorized record
Save the following as server.ts. JWT verification checks the signature, allowed algorithm, token type, issuer, audience and expiry. The middleware also requires invoices:read. Only the verified subject maps to an application user and tenant; neither is accepted as a tool argument. The OAuth client ID identifies the calling client, not the user.
The two in-memory invoices are disposable application data, not a response that echoes the arguments. The query requires the invoice ID, user ID and tenant ID to match. An inaccessible and a nonexistent invoice return the same error without disclosing its value. In your app, replace this lookup with the same authorized service/query used by your normal routes; never substitute an unscoped database read.
import { readFile } from 'node:fs/promises';
import { jwtVerify, errors } from 'jose';
import { z } from 'zod/v4';
import { createMcpExpressApp, requireBearerAuth } from '@modelcontextprotocol/express';
import { toNodeHandler } from '@modelcontextprotocol/node';
import {
createMcpHandler, McpServer, OAuthError, OAuthErrorCode,
type OAuthTokenVerifier,
} from '@modelcontextprotocol/server';
// Local exercise only: never deploy this shared signing key or token issuer.
const key = await readFile('.local-key');
const issuer = 'http://127.0.0.1:3001';
const resource = new URL('http://127.0.0.1:3000/mcp');
const metadataPath = '/.well-known/oauth-protected-resource/mcp';
const users: Record<string, { userId: string; tenantId: string }> = {
alice: { userId: 'user-a', tenantId: 'team-a' },
bob: { userId: 'user-b', tenantId: 'team-b' },
};
// Disposable application data. Production calls the existing authorized data layer.
const invoices = [
{ id: 'inv-a', userId: 'user-a', tenantId: 'team-a', totalCents: 4200 },
{ id: 'inv-b', userId: 'user-b', tenantId: 'team-b', totalCents: 7900 },
];
const verifier: OAuthTokenVerifier = {
async verifyAccessToken(token) {
let payload;
try {
({ payload } = await jwtVerify(token, key, {
algorithms: ['HS256'], typ: 'at+jwt', issuer, audience: resource.href,
requiredClaims: ['exp', 'sub', 'client_id', 'scope'],
}));
} catch (error) {
if (error instanceof errors.JOSEError) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid access token');
}
throw error;
}
const user = typeof payload.sub === 'string' && Object.hasOwn(users, payload.sub)
? users[payload.sub] : undefined;
if (!user || typeof payload.client_id !== 'string' || !payload.client_id ||
typeof payload.scope !== 'string' || typeof payload.exp !== 'number') {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid access token');
}
return {
token, clientId: payload.client_id, scopes: payload.scope.split(' '),
expiresAt: payload.exp, resource, extra: user,
};
},
};
const handler = createMcpHandler(({ authInfo }) => {
const server = new McpServer({ name: 'invoice-reader', version: '1.0.0' });
server.registerTool('read_invoice', {
description: 'Read one draft invoice belonging to the authenticated user and tenant.',
inputSchema: z.strictObject({ invoiceId: z.string().min(1).max(80) }),
annotations: { readOnlyHint: true },
}, async ({ invoiceId }) => {
const user = authInfo?.extra;
const invoice = user && invoices.find(row => row.id === invoiceId &&
row.userId === user.userId && row.tenantId === user.tenantId);
if (!invoice) return {
isError: true, content: [{ type: 'text', text: 'Invoice unavailable' }],
};
return { content: [{ type: 'text', text: JSON.stringify({
id: invoice.id, status: 'draft', currency: 'USD', totalCents: invoice.totalCents,
}) }] };
});
return server;
}, { responseMode: 'json', legacy: 'reject' });
const app = createMcpExpressApp();
// This advertises a local test issuer, not a functioning OAuth login service.
app.get(metadataPath, (_req, res) => res.json({
resource: resource.href, authorization_servers: [issuer],
scopes_supported: ['invoices:read'], bearer_methods_supported: ['header'],
}));
const auth = requireBearerAuth({
verifier, requiredScopes: ['invoices:read'], expectedResource: resource,
resourceMetadataUrl: new URL(metadataPath, resource).href,
});
const node = toNodeHandler(handler);
app.all('/mcp', auth, (req, res) => void node(req, res, req.body));
const listener = app.listen(3000, '127.0.0.1', () => console.log('Listening on ' + resource));
process.on('SIGINT', async () => {
await handler.close();
listener.close();
});Start it with npx tsx server.ts. It binds only to 127.0.0.1. The Express factory rejects untrusted Host/Origin headers; a non-browser client may omit Origin but still needs a valid token. Passing req.body avoids re-reading the stream already consumed by Express's JSON parser.
Each HTTP request gets a fresh MCP server with that request's verified identity. The endpoint uses JSON responses and emits no progress notifications. readOnlyHint describes the tool; it does not enforce permissions. The token checks and scoped query do that.
The public resource-metadata route tells a client which resource and issuer this example names. Its issuer is a local test identifier, not a working login endpoint. The production requirements below explain the separate provider and discovery setup.
3. Prove discovery, authorized reads and denials
In a second terminal in the same directory, save check.ts and run npx tsx check.ts. It signs local test credentials, sends HTTP requests and asserts results. It sends no tokens to a third party and invokes no model. The deliberately invalid credentials are generated only to exercise the verifier.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { randomBytes } from 'node:crypto';
import { SignJWT } from 'jose';
const key = await readFile('.local-key');
const resource = 'http://127.0.0.1:3000/mcp';
const issuer = 'http://127.0.0.1:3001';
const metadataUrl = 'http://127.0.0.1:3000/.well-known/oauth-protected-resource/mcp';
const now = Math.floor(Date.now() / 1000);
let id = 0;
async function token(overrides: Record<string, unknown> = {}, signingKey = key) {
return new SignJWT({
iss: issuer, aud: resource, sub: 'alice', client_id: 'local-check',
scope: 'invoices:read', iat: now, exp: now + 300, ...overrides,
}).setProtectedHeader({ alg: 'HS256', typ: 'at+jwt' }).sign(signingKey);
}
async function rpc(bearer: string | undefined, method = 'tools/list', params: Record<string, unknown> = {}) {
const response = await fetch(resource, {
method: 'POST',
headers: {
'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',
'MCP-Protocol-Version': '2026-07-28', 'Mcp-Method': method,
...(typeof params.name === 'string' ? { 'Mcp-Name': params.name } : {}),
...(bearer ? { Authorization: 'Bearer ' + bearer } : {}),
},
body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params: {
...params, _meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientInfo': { name: 'local-check', version: '1.0.0' },
'io.modelcontextprotocol/clientCapabilities': {},
},
} }),
});
return { response, body: await response.json() };
}
const alice = await token();
const listed = await rpc(alice);
assert.equal(listed.response.status, 200);
assert.deepEqual(listed.body.result.tools.map((t: { name: string }) => t.name), ['read_invoice']);
console.log('tools/list: read_invoice');
for (const [sub, invoiceId, totalCents] of [
['alice', 'inv-a', 4200], ['bob', 'inv-b', 7900],
] as const) {
const read = await rpc(await token({ sub }), 'tools/call', {
name: 'read_invoice', arguments: { invoiceId },
});
assert.equal(read.response.status, 200);
assert.notEqual(read.body.result.isError, true);
assert.deepEqual(JSON.parse(read.body.result.content[0].text), {
id: invoiceId, status: 'draft', currency: 'USD', totalCents,
});
console.log(sub + ': authorized ' + invoiceId + ' = ' + totalCents + ' cents');
}
for (const [label, bearer, status] of [
['missing', undefined, 401],
['malformed', 'not-a-jwt', 401],
['wrong signature', await token({}, randomBytes(32)), 401],
['wrong issuer', await token({ iss: 'http://127.0.0.1:3999' }), 401],
['wrong audience', await token({ aud: resource + '/other' }), 401],
['expired', await token({ exp: now - 60 }), 401],
['missing expiry', await token({ exp: undefined }), 401],
['unknown user', await token({ sub: 'mallory' }), 401],
['insufficient scope', await token({ scope: 'profile' }), 403],
] as const) {
const denied = await rpc(bearer);
assert.equal(denied.response.status, status, label);
assert.equal(denied.body.error, status === 403 ? 'insufficient_scope' : 'invalid_token');
assert.ok(denied.response.headers.get('www-authenticate')?.includes(metadataUrl));
console.log(label + ': ' + status);
}
for (const invoiceId of ['inv-b', 'does-not-exist']) {
const denied = await rpc(alice, 'tools/call', { name: 'read_invoice', arguments: { invoiceId } });
assert.equal(denied.response.status, 200);
assert.equal(denied.body.result.isError, true);
assert.equal(denied.body.result.content[0].text, 'Invoice unavailable');
}
const spoofed = await rpc(alice, 'tools/call', {
name: 'read_invoice', arguments: { invoiceId: 'inv-b', userId: 'bob', tenantId: 'team-b' },
});
assert.ok(spoofed.body.error || spoofed.body.result?.isError);
assert.ok(!JSON.stringify(spoofed.body).includes('7900'));
console.log('cross-user, missing record and identity override: denied without invoice data');
const metadata = await fetch(metadataUrl);
assert.equal(metadata.status, 200);
assert.deepEqual(await metadata.json(), {
resource, authorization_servers: [issuer], scopes_supported: ['invoices:read'],
bearer_methods_supported: ['header'],
});
const origin = await fetch(resource, { method: 'POST', headers: { Origin: 'https://untrusted.example' } });
assert.equal(origin.status, 403);
console.log('resource metadata: OK; untrusted Origin: 403; all checks passed');The script uses the 2026-07-28 request headers and matching per-request metadata, not an older initialize handshake. Both the protocol-version and method/name headers must agree with the body. It expects JSON because this endpoint explicitly selects JSON responses.
- Discovery:
tools/listreturnsread_invoice. - Authorized data: Alice gets
inv-a, USD 4200 cents; Bob getsinv-b, USD 7900 cents. Neither response includes internal user/tenant IDs. - HTTP 401: missing, malformed, wrong-signature, wrong-issuer, wrong-audience, expired, missing-expiry and unknown-user tokens are rejected.
- HTTP 403: a valid token with insufficient scope is rejected. An untrusted Origin is also rejected.
- Application denial: Alice requesting Bob's invoice gets HTTP 200 with a tool result marked
isError: true, not invoice data. A fabricated user/tenant argument cannot grant access. Inspect the MCP result, not just the HTTP status. - Metadata: authorization challenges point to the unauthenticated resource-metadata document, whose resource, issuer and scopes are checked.
Success ends with all checks passed. A failed assertion is a failed boundary check, not a reason to remove the assertion. If you installed the optional type packages, run npx tsc --noEmit --strict --target ES2022 --module NodeNext --moduleResolution NodeNext server.ts check.ts.
Stop the server with Ctrl-C afterward. Delete the disposable project, including its local key, when finished. These checks establish the example's local read boundary, not production security, OAuth interoperability, availability or model quality.
4. Replace the local issuer before deploying
A remote MCP server is an OAuth resource server. Your authorization server issues access tokens; this service verifies them. A browser session cookie, a decoded JWT without signature verification, or an ID token for another audience is not a replacement for an access token issued for this resource.
- Configure a real provider and resource. Register the canonical HTTPS MCP URL and least-privilege scopes with your authorization server. Use its supported OAuth 2.1 flow and client-registration mechanism. User-delegated access needs the applicable authorization-code/PKCE flow; unattended access needs a separately authorized machine identity and business permissions, not a reused human browser cookie.
- Verify according to that provider's token contract. Replace the local shared key and issuer with validated provider configuration. For JWT access tokens, verify using the provider's trusted keys, allowed algorithm, issuer, resource audience and expiry; use authenticated introspection for opaque tokens. Map the verified issuer/subject to your application's server-controlled user and tenant membership. Check revocation/disabled membership as your application requires. Never trust a caller-supplied tenant or pass an MCP access token through to a different upstream API.
- Publish real discovery metadata. Replace the example's resource URL and authorization-server identifier with their HTTPS values. Serve RFC 9728 protected resource metadata at the location advertised in
WWW-Authenticate; the provider must publish RFC 8414 or OpenID Connect discovery. The SDK's authorization guide documentsmcpAuthMetadataRouterfor the resource document and a mirror of provider metadata. Fetch/configure genuine provider metadata, not invented authorize/token URLs. Verify the chosen client's full discovery and login path separately. - Retain transport and service defenses. Terminate TLS, constrain allowed hosts and origins when changing the bind address, and configure any proxy deliberately. Add per-principal rate limits, request/query timeouts, bounded results and audit outcomes without raw tokens or sensitive invoice contents. Scope every database operation and keep database credentials server-side. Read-only data can still be sensitive and returned text can contain untrusted instructions.
The SDK warns that Express adapter 2.0.1 does not forward expectedResource; this example pins 2.0.2 and also validates audience inside jwtVerify. Keep the wrong-audience check when upgrading. Do not remove audience validation just because a token has a valid signature.
Start read-only. Before adding writes, enforce operation-specific permissions and business validation, bind confirmation to the exact action/arguments where needed, and design idempotency and outcome recovery for retries. A tool annotation or a client's approval UI is not server authorization. An ambiguous response does not prove a write failed or make replay safe. This example implements no writes or scheduler.
If the real task is in the page, test that instead
Keep this backend approach for service data access or work that must not depend on a tab. If your users instead want help navigating, editing and saving through existing pages, Bunkhouse can supply the attended interaction layer rather than asking you to build a pane, discovery system, execution sandbox and review UI. Setup still includes identity integration, permissions and hints for operations discovery cannot see.
A free coding-agent trial can check that fit on a disposable page with no account, card or model API key. Your coding agent supplies inference and must keep serving turns. Use dummy data: what the assistant reads travels through the service to the coding agent. With auto-approval off, read one saved record, reject an edit and confirm no saved change, then approve it and verify the exact saved result using the evaluation checklist.
Actions classified as write or unknown ask for review by default; read-classified actions do not. Site-permitted, user-selected auto-approval can change review behavior. Your backend remains responsible for authorization; see Security. The trial evaluates attended page integration, not this backend MCP endpoint, Bunkhouse's external-client relay or hosted-model quality. Production installation and billing are separate.