From cb4f31794a608e27024b6f43f89d75320517870f Mon Sep 17 00:00:00 2001 From: willynikes2 Date: Tue, 13 Oct 2026 12:12:07 +0000 Subject: [PATCH] fix(mcp): tell ChatGPT the tools need OAuth and which scopes to request A ChatGPT plugin pointed at /mcp installed with no Connect button. The OAuth flow itself works (registration, sign-in, consent, token, search); what was missing is everything ChatGPT reads to decide to offer sign-in: - tools/list now carries securitySchemes (oauth2) on every tool, as a top-level field and in _meta (the SDK only passes _meta through) - the 401 challenge names the scopes to request - the protected resource metadata lists scopes_supported; the mcp plugin leaves identity and refresh scopes out, so a client had no hint to ask for offline_access README documents the plugin mcp.json auth block (oauth + dcr), which the plugin package needs for the button to appear. Co-Authored-By: Claude Opus 5.5 --- README.md | 30 +++++++++++++++ src/auth-oauth.js | 21 +++++++++++ src/mcp-http.js | 21 ++++++++++- src/server.js | 8 ++-- tests/auth-oauth.test.js | 34 ++++++++++++++++- tests/helpers/oauth-flow.js | 4 +- tests/mcp-http.test.js | 73 +++++++++++++++++++++++++++++++++++++ 7 files changed, 182 insertions(+), 9 deletions(-) create mode 100644 tests/mcp-http.test.js diff --git a/README.md b/README.md index 90b6636..3cc8ecc 100644 --- a/README.md +++ b/README.md @@ -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 `. Public sign-up is off. + ### ChatGPT Custom GPTs (REST API) 1. Import the OpenAPI spec from `https://your-domain.com/openapi.json` diff --git a/src/auth-oauth.js b/src/auth-oauth.js index 09341f9..e5cd484 100644 --- a/src/auth-oauth.js +++ b/src/auth-oauth.js @@ -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 @@ -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 { diff --git a/src/mcp-http.js b/src/mcp-http.js index ad8b0bc..9256128 100644 --- a/src/mcp-http.js +++ b/src/mcp-http.js @@ -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; } diff --git a/src/server.js b/src/server.js index d6ca106..447afd4 100644 --- a/src/server.js +++ b/src/server.js @@ -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'; @@ -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) => { @@ -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.' }); }; diff --git a/tests/auth-oauth.test.js b/tests/auth-oauth.test.js index 4e2c722..fdb008a 100644 --- a/tests/auth-oauth.test.js +++ b/tests/auth-oauth.test.js @@ -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); @@ -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'); + }); }); diff --git a/tests/helpers/oauth-flow.js b/tests/helpers/oauth-flow.js index 255eeef..55b2c79 100644 --- a/tests/helpers/oauth-flow.js +++ b/tests/helpers/oauth-flow.js @@ -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'); @@ -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); diff --git a/tests/mcp-http.test.js b/tests/mcp-http.test.js new file mode 100644 index 0000000..5bf48cf --- /dev/null +++ b/tests/mcp-http.test.js @@ -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); + }); +});