Add an MCP server for the API, deployable next to the application
Some checks failed
Tests / lint (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / test-postgres (push) Has been cancelled
Tests / mcp (push) Has been cancelled

mcp/ exposes both APIs as MCP tools, one per operation in openapi.yaml,
named after the Laravel route each lands on (public_projects_index,
admin_pages_update, ...). Nothing is written by hand: the tools are
derived from the document the target application serves, which the
contract tests already hold to the truth.

Two transports over one core:

- stdio (`node mcp/server.mjs`), registered in .mcp.json, signing in
  with credentials from the environment and refreshing the token.
- Streamable HTTP (`--http`), stateless, deployed as the landing-mcp
  service. It holds no credentials: each request brings its caller's
  Pireon Basic credentials or bearer token, so the API applies that
  person's permissions. Sessions live in memory keyed by a hash,
  refused credentials are remembered for a minute, and the spec is
  reloaded every minute so new endpoints appear without a redeploy.

Left out on purpose: the token exchange, telemetry, and the contact and
apply forms, which notify real people. The preview secret is never sent
for anonymous callers, and is unset in the deployment by default.

A CI job runs the Node tests, including the HTTP mode end to end
against a fake application.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-27 21:58:14 +02:00
parent 5ca084bd4a
commit 748b485c9b
20 changed files with 2862 additions and 2 deletions

151
mcp/test/client.test.mjs Normal file
View File

@@ -0,0 +1,151 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { LandingClient } from '../src/client.mjs';
const showPage = {
method: 'GET',
path: '/v1/pages/{page}',
params: [{ name: 'page', in: 'path' }, { name: 'lang', in: 'query' }],
hasBody: false,
requiresAuth: true,
};
const publicProjects = {
method: 'GET',
path: '/public/v1/projects',
params: [{ name: 'featured', in: 'query' }],
hasBody: false,
requiresAuth: false,
};
/** A fake fetch that answers from a list of handlers and records every call. */
function fakeFetch(handler) {
const calls = [];
const fetch = async (url, init) => {
calls.push({ url, ...init });
const { status = 200, body = {} } = handler(url, init, calls.length);
return new Response(status === 204 ? null : JSON.stringify(body), { status });
};
return { fetch, calls };
}
const tokenResponse = (access, expiresInMs = 3_600_000) => ({
access_token: access,
refresh_token: `refresh-${access}`,
expires_at: new Date(Date.now() + expiresInMs).toISOString(),
});
test('builds the URL from path and query parameters', async () => {
const { fetch, calls } = fakeFetch(() => ({ body: { data: [] } }));
const client = new LandingClient({ apiBase: 'http://app.test/api/', fetch });
await client.call(publicProjects, { featured: true });
assert.equal(calls[0].url, 'http://app.test/api/public/v1/projects?featured=1');
assert.equal(calls[0].headers.Authorization, undefined);
});
test('sends the preview secret on public calls only', async () => {
const { fetch, calls } = fakeFetch((url) => (
url.endsWith('/auth/token') ? { body: tokenResponse('a') } : { body: {} }
));
const client = new LandingClient({
apiBase: 'http://app.test/api', username: 'u', password: 'p', previewToken: 'secret', fetch,
});
await client.call(publicProjects, {});
await client.call(showPage, { page: 1 });
assert.equal(calls[0].headers['X-Preview-Token'], 'secret');
assert.equal(calls.at(-1).headers['X-Preview-Token'], undefined);
});
test('logs in once and reuses the token', async () => {
const { fetch, calls } = fakeFetch((url) => (
url.endsWith('/auth/token') ? { body: tokenResponse('a') } : { body: { data: {} } }
));
const client = new LandingClient({ apiBase: 'http://app.test/api', username: 'u', password: 'p', fetch });
await Promise.all([client.call(showPage, { page: 1 }), client.call(showPage, { page: 2 })]);
await client.call(showPage, { page: 3 });
assert.equal(calls.filter((c) => c.url.endsWith('/auth/token')).length, 1);
assert.equal(calls.at(-1).url, 'http://app.test/api/v1/pages/3');
assert.equal(calls.at(-1).headers.Authorization, 'Bearer a');
});
test('refreshes a token about to expire', async () => {
let issued = 0;
const { fetch, calls } = fakeFetch((url) => (
url.endsWith('/auth/token') ? { body: tokenResponse(`t${++issued}`, 10_000) } : { body: {} }
));
const client = new LandingClient({ apiBase: 'http://app.test/api', username: 'u', password: 'p', fetch });
await client.call(showPage, { page: 1 });
await client.call(showPage, { page: 1 });
const grants = calls.filter((c) => c.url.endsWith('/auth/token')).map((c) => JSON.parse(c.body).grant_type);
assert.deepEqual(grants, ['password', 'refresh_token']);
assert.equal(calls.at(-1).headers.Authorization, 'Bearer t2');
});
test('retries once with a new token after a 401', async () => {
let issued = 0;
const { fetch, calls } = fakeFetch((url, init) => {
if (url.endsWith('/auth/token')) return { body: tokenResponse(`t${++issued}`) };
return init.headers.Authorization === 'Bearer t1' ? { status: 401, body: { message: 'Unauthenticated.' } } : { body: { ok: true } };
});
const client = new LandingClient({ apiBase: 'http://app.test/api', username: 'u', password: 'p', fetch });
const response = await client.call(showPage, { page: 1 });
assert.equal(response.status, 200);
assert.equal(calls.at(-1).headers.Authorization, 'Bearer t2');
});
test('falls back to the password when the refresh token is refused', async () => {
let issued = 0;
const { fetch, calls } = fakeFetch((url, init) => {
if (!url.endsWith('/auth/token')) return { body: {} };
return JSON.parse(init.body).grant_type === 'refresh_token'
? { status: 422, body: { message: 'invalid' } }
: { body: tokenResponse(`t${++issued}`, 10_000) };
});
const client = new LandingClient({ apiBase: 'http://app.test/api', username: 'u', password: 'p', fetch });
await client.call(showPage, { page: 1 });
await client.call(showPage, { page: 1 });
const grants = calls.filter((c) => c.url.endsWith('/auth/token')).map((c) => JSON.parse(c.body).grant_type);
assert.deepEqual(grants, ['password', 'refresh_token', 'password']);
});
test('a fixed token is used as is and never renewed', async () => {
const { fetch, calls } = fakeFetch(() => ({ status: 401, body: {} }));
const client = new LandingClient({ apiBase: 'http://app.test/api', token: 'fixed', fetch });
const response = await client.call(showPage, { page: 1 });
assert.equal(response.status, 401);
assert.equal(calls.length, 1);
assert.equal(calls[0].headers.Authorization, 'Bearer fixed');
});
test('refuses an authenticated call without credentials', async () => {
const client = new LandingClient({ apiBase: 'http://app.test/api', fetch: async () => assert.fail('no request') });
await assert.rejects(client.call(showPage, { page: 1 }), /LANDING_TOKEN/);
});
test('refuses a call missing a path parameter', async () => {
const client = new LandingClient({ apiBase: 'http://app.test/api', token: 't', fetch: async () => assert.fail('no request') });
await assert.rejects(client.call(showPage, {}), /"page"/);
});

155
mcp/test/http.test.mjs Normal file
View File

@@ -0,0 +1,155 @@
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { after, before, test } from 'node:test';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { Catalogue } from '../src/catalogue.mjs';
import { parseAuthorization, startHttpServer } from '../src/http.mjs';
const spec = await readFile(new URL('../../public/openapi.yaml', import.meta.url), 'utf8');
/**
* Stands in for the application: the spec, the token endpoint, /v1/me and one
* public endpoint that reports whether it was sent the preview secret.
*/
const app = { logins: 0, requests: [] };
const appServer = createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : null;
app.requests.push({ url: req.url, headers: req.headers });
const json = (status, payload) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(payload));
};
if (req.url === '/openapi.yaml') return res.end(spec);
if (req.url === '/api/v1/auth/token') {
app.logins++;
return body.username === 'ada@example.com' && body.password === 'secret'
? json(200, { access_token: 'ada-token', refresh_token: 'r', expires_at: new Date(Date.now() + 3_600_000).toISOString() })
: json(422, { message: 'These credentials do not match our records.' });
}
if (req.url.startsWith('/api/v1/')) {
return ['Bearer ada-token', 'Bearer valid-token'].includes(req.headers.authorization)
? json(200, { data: { email: 'ada@example.com' } })
: json(401, { message: 'Unauthenticated.' });
}
if (req.url.startsWith('/api/public/v1/site')) {
return json(200, { data: { preview: req.headers['x-preview-token'] === 'drafts' } });
}
json(404, { message: 'Not found' });
});
let mcpUrl;
let mcpServer;
before(async () => {
appServer.listen(0, '127.0.0.1');
await once(appServer, 'listening');
const appUrl = `http://127.0.0.1:${appServer.address().port}`;
mcpServer = startHttpServer({
catalogue: new Catalogue({ source: `${appUrl}/openapi.yaml`, baseUrl: appUrl }),
port: 0,
host: '127.0.0.1',
previewToken: 'drafts',
});
await once(mcpServer, 'listening');
mcpUrl = new URL(`http://127.0.0.1:${mcpServer.address().port}/mcp`);
});
after(() => {
mcpServer.close();
appServer.close();
});
async function connect(authorization) {
const client = new Client({ name: 'test', version: '0' });
const headers = authorization ? { Authorization: authorization } : {};
await client.connect(new StreamableHTTPClientTransport(mcpUrl, { requestInit: { headers } }));
return client;
}
const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`;
test('an anonymous caller gets the public API, without the preview secret', async () => {
const client = await connect();
const { tools } = await client.listTools();
assert.ok(tools.length > 0);
assert.ok(tools.every((tool) => tool.name.startsWith('public_')));
const result = await client.callTool({ name: 'public_site', arguments: {} });
assert.match(result.content[0].text, /"preview":false/);
await client.close();
});
test('Basic credentials get both APIs, and sign in once across requests', async () => {
const before = app.logins;
for (let i = 0; i < 3; i++) {
const client = await connect(basic('ada@example.com', 'secret'));
const { tools } = await client.listTools();
assert.ok(tools.some((tool) => tool.name === 'admin_pages_update'));
const me = await client.callTool({ name: 'admin_me', arguments: {} });
assert.equal(me.isError, false);
const site = await client.callTool({ name: 'public_site', arguments: {} });
assert.match(site.content[0].text, /"preview":true/);
await client.close();
}
assert.equal(app.logins - before, 1);
});
test('wrong credentials are a 401, remembered rather than retried', async () => {
const before = app.logins;
for (let i = 0; i < 2; i++) {
await assert.rejects(connect(basic('ada@example.com', 'wrong')), /401|Credentials refused/);
}
assert.equal(app.logins - before, 1);
});
test('a bearer token is checked against the application', async () => {
const good = await connect('Bearer valid-token');
assert.ok((await good.listTools()).tools.some((tool) => tool.name === 'admin_me'));
await good.close();
await assert.rejects(connect('Bearer revoked-token'), /401|refused/);
});
test('only POST /mcp is served, and /up answers without the application', async () => {
const base = `http://127.0.0.1:${mcpServer.address().port}`;
assert.equal((await fetch(`${base}/up`)).status, 200);
assert.equal((await fetch(`${base}/mcp`)).status, 405);
assert.equal((await fetch(`${base}/elsewhere`)).status, 404);
});
test('parses Authorization headers', () => {
assert.deepEqual(parseAuthorization(basic('a@b.c', 'p:with:colons')), { username: 'a@b.c', password: 'p:with:colons' });
assert.deepEqual(parseAuthorization('bearer abc'), { token: 'abc' });
assert.equal(parseAuthorization(basic('', 'p')), null);
assert.equal(parseAuthorization('Digest abc'), null);
});

81
mcp/test/tools.test.mjs Normal file
View File

@@ -0,0 +1,81 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { test } from 'node:test';
import { parse } from 'yaml';
import { buildTools } from '../src/tools.mjs';
// The document in this checkout: the one the application serves.
const spec = parse(await readFile(new URL('../../public/openapi.yaml', import.meta.url), 'utf8'));
const tools = buildTools(spec);
const byName = new Map(tools.map((tool) => [tool.name, tool]));
test('names follow the Laravel routes', () => {
const expected = {
public_site: 'GET /public/v1/site',
public_good_first_issues: 'GET /public/v1/good-first-issues',
public_projects_index: 'GET /public/v1/projects',
public_projects_show: 'GET /public/v1/projects/{slug}',
public_clients: 'GET /public/v1/clients',
admin_me: 'GET /v1/me',
admin_pages_index: 'GET /v1/pages',
admin_pages_store: 'POST /v1/pages',
admin_pages_update: 'PATCH /v1/pages/{page}',
admin_pages_destroy: 'DELETE /v1/pages/{page}',
admin_pages_restore: 'POST /v1/pages/{page}/restore',
admin_roles_catalogue: 'GET /v1/roles/catalogue',
};
for (const [name, route] of Object.entries(expected)) {
const tool = byName.get(name);
assert.ok(tool, `missing ${name}`);
assert.equal(`${tool.operation.method} ${tool.operation.path}`, route);
}
});
test('names are valid MCP tool names', () => {
for (const { name } of tools) assert.match(name, /^[a-z0-9_]{1,64}$/);
});
test('leaves out what is not for an operator', () => {
const routes = tools.map(({ operation }) => `${operation.method} ${operation.path}`);
assert.ok(!routes.includes('POST /v1/auth/token'));
assert.ok(!routes.some((route) => route.includes('/telemetry/')));
assert.ok(!routes.includes('POST /public/v1/contact'));
assert.ok(!routes.includes('POST /public/v1/calls/{slug}/apply'));
});
test('every other documented operation is a tool', () => {
const documented = Object.values(spec.paths)
.flatMap((item) => ['get', 'post', 'put', 'patch', 'delete'].filter((m) => item[m])).length;
// auth/token, two telemetry endpoints, contact and apply.
assert.equal(tools.length, documented - 5);
});
test('schemas are self-contained JSON Schema', () => {
for (const tool of tools) {
const json = JSON.stringify(tool.inputSchema);
assert.ok(!json.includes('"$ref"'), `${tool.name} still has a $ref`);
assert.ok(!json.includes('"nullable"'), `${tool.name} still has nullable`);
}
});
test('path parameters are required, headers are not offered', () => {
const show = byName.get('public_projects_show');
assert.deepEqual(show.inputSchema.required, ['slug']);
assert.ok(!('X-Preview-Token' in show.inputSchema.properties));
});
test('a create requires its fields, an update does not', () => {
assert.deepEqual(byName.get('admin_pages_store').inputSchema.properties.body.required, ['title', 'slug']);
assert.equal(byName.get('admin_pages_update').inputSchema.properties.body.required, undefined);
});
test('only the admin API is marked as needing a token', () => {
for (const tool of tools) {
assert.equal(tool.operation.requiresAuth, tool.name.startsWith('admin_'), tool.name);
}
});