Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,36 @@ Point your MCP client at the stdio transport:
}
```

### ChatGPT plugin (remote MCP with OAuth)

The HTTP MCP endpoint at `https://your-domain.com/mcp` signs clients in through OAuth. A ChatGPT plugin only shows its Connect button when the plugin's `mcp.json` declares that. Without the `auth` block, ChatGPT treats the server as needing no sign-in, and the server refuses every request.

```json
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
"mcpServers": {
"knowledge-base": {
"type": "streamable-http",
"url": "https://your-domain.com/mcp",
"extensions": {
"com.openai": {
"auth": {
"type": "oauth",
"client": { "mode": "dcr" },
"baseScopes": ["openid", "offline_access"]
}
}
}
}
}
}
```

- `dcr`: ChatGPT registers itself as an OAuth client. The package holds no client ID, secret or API key.
- Endpoints are found through discovery (`/.well-known/oauth-protected-resource/mcp`), so no URL overrides are needed.
- `offline_access` gets ChatGPT a refresh token. Without it you sign in again every hour.
- Sign in with the account created by `kb auth add-user <email>`. Public sign-up is off.

### ChatGPT Custom GPTs (REST API)

1. Import the OpenAPI spec from `https://your-domain.com/openapi.json`
Expand Down
21 changes: 21 additions & 0 deletions src/auth-oauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export const BASE_URL = (process.env.BETTER_AUTH_URL || `http://localhost:${proc
export const MCP_RESOURCE = `${BASE_URL}/mcp`;
const ACCEPTED_AUDIENCES = [MCP_RESOURCE, BASE_URL];

/** Scopes an MCP client should request: an identity, plus a refresh token so it stays connected. */
export const MCP_SCOPES = ['openid', 'offline_access'];
const RESOURCE_METADATA_URL = `${BASE_URL}/.well-known/oauth-protected-resource/mcp`;

const authDb = new Database(AUTH_DB_PATH);

// better-auth stores string[] columns as TEXT on SQLite, then warns about it on
Expand Down Expand Up @@ -120,6 +124,23 @@ export async function addUser({ email, password, name }) {
return user;
}

/** RFC 9728 challenge that points an unauthenticated MCP client at the OAuth flow. */
export const mcpChallenge = () => `Bearer resource_metadata="${RESOURCE_METADATA_URL}", scope="${MCP_SCOPES.join(' ')}"`;

/**
* RFC 9728 protected resource metadata for the MCP endpoint. The mcp plugin leaves
* identity and refresh scopes out of it; clients such as ChatGPT read scopes_supported
* to decide what to request, so the scopes this server needs are added here.
*/
export async function protectedResourceMetadata(path) {
const res = await auth.handler(new Request(`${BASE_URL}${path}`));
if (!res.ok) return res;
const metadata = await res.json();
const headers = new Headers(res.headers);
headers.delete('content-length');
return Response.json({ ...metadata, scopes_supported: metadata.scopes_supported ?? MCP_SCOPES }, { headers });
}

/** Verify an OAuth access token (a JWT signed by this server). Returns its claims or null. */
export async function verifyAccessToken(token) {
try {
Expand Down
21 changes: 19 additions & 2 deletions src/mcp-http.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
import { randomUUID } from 'crypto';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { getHttpToolDefinitions } from './tools.js';
import { MCP_SCOPES } from './auth-oauth.js';

// Every tool needs an OAuth token. ChatGPT reads securitySchemes to offer sign-in
// rather than calling anonymously.
const SECURITY_SCHEMES = [{ type: 'oauth2', scopes: MCP_SCOPES }];

/**
* Create a fresh MCP server instance with all HTTP-safe tools registered.
* A new instance is created per session to keep state isolated.
*/
function createMcpServer() {
export function createMcpServer() {
const server = new McpServer({
name: 'knowledge-base-brain',
version: '1.0.0',
});

for (const tool of getHttpToolDefinitions()) {
server.tool(tool.name, tool.description, tool.schema, tool.handler);
server.registerTool(tool.name, {
description: tool.description,
inputSchema: tool.schema,
_meta: { securitySchemes: SECURITY_SCHEMES },
}, tool.handler);
}

// The SDK only passes _meta through to tools/list; ChatGPT also reads the top-level field.
const listTools = server.server._requestHandlers.get('tools/list');
server.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
const result = await listTools(request, extra);
return { ...result, tools: result.tools.map(tool => ({ ...tool, securitySchemes: SECURITY_SCHEMES })) };
});

return server;
}

Expand Down
8 changes: 4 additions & 4 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import authRoutes from './routes/session-routes.js';
import apiRoutes from './routes/api.js';
import { toNodeHandler } from 'better-auth/node';
import { oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from '@better-auth/oauth-provider';
import { auth, migrateAuthSchema, verifyAccessToken, BASE_URL } from './auth-oauth.js';
import { auth, migrateAuthSchema, verifyAccessToken, mcpChallenge, protectedResourceMetadata, BASE_URL } from './auth-oauth.js';
import { createApiKeyMiddleware } from './middleware/api-key.js';
import v1Router from './routes/v1.js';
import openapiRoute from './routes/openapi.js';
Expand Down Expand Up @@ -110,9 +110,9 @@ export async function start() {
corsMiddleware, metadataRoute(authServerMetadata));
app.get(['/.well-known/openid-configuration', '/.well-known/openid-configuration/api/auth'],
corsMiddleware, metadataRoute(openIdMetadata));
// RFC 9728 protected resource metadata, served by the mcp plugin itself.
// RFC 9728 protected resource metadata: the mcp plugin's document plus the scopes to request.
app.get(['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp'],
corsMiddleware, toNodeHandler(auth));
corsMiddleware, async (req, res) => sendWebResponse(await protectedResourceMetadata(req.path), res));

// --- Sign-in page for OAuth consent flow ---
app.get('/sign-in', (req, res) => {
Expand Down Expand Up @@ -172,7 +172,7 @@ export async function start() {
}

// RFC 9728: point MCP clients at the metadata that starts the OAuth flow.
res.setHeader('WWW-Authenticate', `Bearer resource_metadata="${BASE_URL}/.well-known/oauth-protected-resource/mcp"`);
res.setHeader('WWW-Authenticate', mcpChallenge());
return res.status(401).json({ error: 'Missing or invalid authentication. Provide X-API-Key header or OAuth Bearer token.' });
};

Expand Down
34 changes: 33 additions & 1 deletion tests/auth-oauth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ const OWNER = { email: 'owner@example.test', password: 'correct horse battery st
let auth;
let oauth;
let verifyAccessToken;
let mcpChallenge;
let protectedResourceMetadata;
let MCP_SCOPES;

describe('OAuth provider access', () => {
before(async () => {
const mod = await import('../src/auth-oauth.js');
({ auth, verifyAccessToken } = mod);
({ auth, verifyAccessToken, mcpChallenge, protectedResourceMetadata, MCP_SCOPES } = mod);
assert.deepEqual(await mod.migrateAuthSchema(), [], 'a fresh database has nothing to archive');
await mod.addUser(OWNER);
oauth = createOAuthClient(auth, BASE);
Expand Down Expand Up @@ -93,4 +96,33 @@ describe('OAuth provider access', () => {
assert.equal(await verifyAccessToken(`${header}.${forgedPayload}.${signature}`), null, 'modified claims were accepted');
assert.equal(await verifyAccessToken(`${header}.${payload}.${signature.slice(0, -4)}AAAA`), null, 'bad signature was accepted');
});

it('tells unauthenticated MCP clients where to start and which scopes to ask for', async () => {
const challenge = mcpChallenge();
assert.match(challenge, /^Bearer /);
assert.ok(challenge.includes(`resource_metadata="${BASE}/.well-known/oauth-protected-resource/mcp"`), challenge);
assert.ok(challenge.includes(`scope="${MCP_SCOPES.join(' ')}"`), challenge);
});

it('publishes the MCP resource, its authorization server and the scopes to request', async () => {
for (const path of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp']) {
const res = await protectedResourceMetadata(path);
assert.equal(res.status, 200, path);
const metadata = await res.json();
assert.equal(metadata.resource, `${BASE}/mcp`);
assert.deepEqual(metadata.authorization_servers, [`${BASE}/api/auth`]);
assert.deepEqual(metadata.scopes_supported, MCP_SCOPES);
}
});

it('gives a client that asks for exactly the advertised scopes a usable, refreshable token', async () => {
const { cookie } = await oauth.signIn(OWNER.email, OWNER.password);
const grant = await oauth.authorize(cookie, { scope: MCP_SCOPES.join(' ') });
const tokens = await oauth.exchange(grant);

assert.ok(await verifyAccessToken(tokens.access_token), 'access token was not accepted');
assert.ok(tokens.refresh_token, 'no refresh token: the client would have to sign in again every hour');
const refreshed = await oauth.refresh(grant, tokens.refresh_token);
assert.ok(await verifyAccessToken(refreshed.access_token), 'refreshed access token was not accepted');
});
});
4 changes: 2 additions & 2 deletions tests/helpers/oauth-flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function createOAuthClient(auth, baseUrl) {
}

/** Runs the flow up to the consent decision. Returns what the token step needs. */
async function authorize(cookie, { resource = `${baseUrl}/mcp`, accept = true } = {}) {
async function authorize(cookie, { resource = `${baseUrl}/mcp`, accept = true, scope = 'openid profile email offline_access' } = {}) {
const meta = await metadata();
const clientId = await register(meta);
const verifier = randomBytes(32).toString('base64url');
Expand All @@ -52,7 +52,7 @@ export function createOAuthClient(auth, baseUrl) {
redirect_uri: REDIRECT_URI,
code_challenge: createHash('sha256').update(verifier).digest('base64url'),
code_challenge_method: 'S256',
scope: 'openid profile email offline_access',
scope,
state: 'state-123',
});
if (resource) query.set('resource', resource);
Expand Down
73 changes: 73 additions & 0 deletions tests/mcp-http.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// tests/mcp-http.test.js — what the HTTP MCP server tells clients about its tools
// Runs the real server over an in-memory transport, against an isolated HOME.
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';

const HOME = mkdtempSync(join(tmpdir(), 'kb-mcp-http-test-'));
process.env.HOME = HOME;
process.env.BETTER_AUTH_URL = 'http://localhost:3838';
process.env.BETTER_AUTH_SECRET = 'test-secret-0123456789abcdef0123456789abcdef';

let createMcpServer;
let MCP_SCOPES;

/** Send one JSON-RPC request and return the raw result, exactly as it goes over the wire. */
async function listToolsRaw() {
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
await createMcpServer().connect(serverSide);
const replies = new Map();
const waiters = new Map();
clientSide.onmessage = (message) => {
if (waiters.has(message.id)) waiters.get(message.id)(message);
else replies.set(message.id, message);
};
await clientSide.start();
const request = (id, method, params) => new Promise((resolve) => {
waiters.set(id, resolve);
clientSide.send({ jsonrpc: '2.0', id, method, params });
});
await request(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } });
await clientSide.send({ jsonrpc: '2.0', method: 'notifications/initialized' });
const { result } = await request(2, 'tools/list', {});
await clientSide.close();
return result.tools;
}

describe('HTTP MCP tool list', () => {
before(async () => {
({ createMcpServer } = await import('../src/mcp-http.js'));
({ MCP_SCOPES } = await import('../src/auth-oauth.js'));
});

after(() => {
rmSync(HOME, { recursive: true, force: true });
});

it('declares OAuth on every tool, so ChatGPT offers sign-in instead of calling anonymously', async () => {
const tools = await listToolsRaw();
assert.ok(tools.some(t => t.name === 'kb_search'), 'kb_search is missing from the tool list');
const expected = [{ type: 'oauth2', scopes: MCP_SCOPES }];
for (const tool of tools) {
assert.deepEqual(tool.securitySchemes, expected, `${tool.name} has no top-level securitySchemes`);
assert.deepEqual(tool._meta?.securitySchemes, expected, `${tool.name} has no _meta.securitySchemes`);
}
});

it('never marks a tool as callable without authentication', async () => {
for (const tool of await listToolsRaw()) {
const schemes = [...(tool.securitySchemes ?? []), ...(tool._meta?.securitySchemes ?? [])];
assert.ok(!schemes.some(s => s.type === 'noauth'), `${tool.name} is marked noauth`);
}
});

it('keeps each tool\'s name, description and input schema', async () => {
const search = (await listToolsRaw()).find(t => t.name === 'kb_search');
assert.ok(search.description.length > 0);
assert.equal(search.inputSchema.type, 'object');
assert.ok('query' in search.inputSchema.properties);
});
});
Loading