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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { GET, OPTIONS } from '../route';

export const dynamic = 'force-dynamic';
15 changes: 15 additions & 0 deletions apps/web/src/app/.well-known/oauth-authorization-server/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { authorizationServerMetadata, CORS_HEADERS } from '@/lib/mcp-oauth';

export const dynamic = 'force-dynamic';

// RFC 8414 authorization server metadata. The [...path] sibling answers the
// path-suffixed form some clients try first.
export function GET() {
return Response.json(authorizationServerMetadata(), {
headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' },
});
}

export function OPTIONS() {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { GET, OPTIONS } from '../route';

export const dynamic = 'force-dynamic';
15 changes: 15 additions & 0 deletions apps/web/src/app/.well-known/oauth-protected-resource/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { CORS_HEADERS, protectedResourceMetadata } from '@/lib/mcp-oauth';

export const dynamic = 'force-dynamic';

// RFC 9728 protected-resource metadata for the MCP server at /api/agent/mcp. The
// [...path] sibling answers the path-suffixed form (/.well-known/oauth-protected-resource/api/agent/mcp).
export function GET() {
return Response.json(protectedResourceMetadata(), {
headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' },
});
}

export function OPTIONS() {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
14 changes: 14 additions & 0 deletions apps/web/src/app/.well-known/openid-configuration/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { CORS_HEADERS, openidConfiguration } from '@/lib/mcp-oauth';

export const dynamic = 'force-dynamic';

// For MCP clients that only look for OpenID discovery. No id_token is issued.
export function GET() {
return Response.json(openidConfiguration(), {
headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' },
});
}

export function OPTIONS() {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
19 changes: 17 additions & 2 deletions apps/web/src/app/api/agent/mcp/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,27 @@ describe('MCP route (e2e)', () => {
authenticateAgentMock.mockResolvedValue({ token: { scopes: ['read', 'trade:crypto'] }, scopes: ['read', 'trade:crypto'], tokenId: 't', userId: 'u', admin: {} });
});

it('handles initialize without auth and advertises tool capability', async () => {
it('answers initialize without a credential with 401 + WWW-Authenticate (starts OAuth)', async () => {
const { POST } = await importRoute();
const res = await POST(rpc('initialize', {}, 1, false) as never);
expect(res.status).toBe(401);
expect(res.headers.get('www-authenticate')).toContain('resource_metadata="https://b1dz.com/.well-known/oauth-protected-resource"');
expect(authenticateAgentMock).not.toHaveBeenCalled();
});

it('handles initialize with an agent token and advertises tool capability', async () => {
const { POST } = await importRoute();
const res = await POST(rpc('initialize', { protocolVersion: '2025-06-18' }) as never);
const body = await res.json();
expect(body.result.serverInfo.name).toBe('b1dz-agent');
expect(body.result.protocolVersion).toBe('2025-06-18');
expect(body.result.capabilities.tools).toBeDefined();
});

it('rejects a bad JSON-RPC envelope with 400', async () => {
const { POST } = await importRoute();
const bad = new Request('http://test.local/api/agent/mcp', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ foo: 'bar' }),
method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer b1dz_agent_test' }, body: JSON.stringify({ foo: 'bar' }),
});
const res = await POST(bad as never);
expect(res.status).toBe(400);
Expand All @@ -62,6 +71,11 @@ describe('MCP route (e2e)', () => {
const body = await res.json();
const names = (body.result.tools as Array<{ name: string }>).map((t) => t.name).sort();
expect(names).toEqual(['get_budget', 'get_portfolio', 'get_quote', 'place_order']);
expect(body.result).toMatchObject({ resultType: 'complete', cacheScope: 'public' });
expect(typeof body.result.ttlMs).toBe('number');
const order = body.result.tools.find((t: { name: string }) => t.name === 'place_order');
expect(order.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true });
for (const t of body.result.tools) expect(t.title).toBeTruthy();
});

it('401s tool calls without a valid agent token', async () => {
Expand All @@ -71,6 +85,7 @@ describe('MCP route (e2e)', () => {
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error.code).toBe(-32001);
expect(res.headers.get('www-authenticate')).toContain('error="invalid_token"');
});

it('routes tools/call place_order through placeAgentOrder', async () => {
Expand Down
89 changes: 72 additions & 17 deletions apps/web/src/app/api/agent/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,59 @@
import type { NextRequest } from 'next/server';
import { authenticateAgent, type AuthedAgent } from '@/lib/api-auth';
import { ACCESS_PREFIX, CORS_HEADERS, resolveAccessToken, resourceMetadataUrl, SCOPE } from '@/lib/mcp-oauth';
import { createAdminSupabase } from '@/lib/supabase';
import { getAgentBudget, getAgentPortfolio, getAgentQuote, placeAgentOrder } from '@/lib/agent-trade';

export const dynamic = 'force-dynamic';

/**
* MCP server (the Base-MCP analog) — exposes b1dz crypto trading to external AI
* agents (Claude, ChatGPT, any MCP client) as tools, over MCP's JSON-RPC HTTP
* transport. Auth is the same scoped agent token (Authorization: Bearer
* b1dz_agent_…); every tool funnels through the shared policy in agent-trade.ts,
* so trades stay hard-capped by the token's sub-account budget.
* transport. Auth: a scoped agent token (Authorization: Bearer b1dz_agent_…) or
* an OAuth 2.1 access token (b1dz_oat_…, see lib/mcp-oauth.ts) whose grant is
* backed by its own agent token. Either way every tool funnels through the
* shared policy in agent-trade.ts, so trades stay hard-capped by that
* sub-account's budget.
*
* Any request without a valid credential is HTTP 401 with
* `WWW-Authenticate: Bearer resource_metadata=…` (MCP authorization spec), so
* connector UIs (claude.ai, ChatGPT) start OAuth on the first request.
*/

const PROTOCOL_VERSION = '2024-11-05';
/** Newest first; an initialize asking for one of these gets it back, anything else gets the newest. */
const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];

const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;

const TOOLS = [
{
name: 'get_budget',
title: 'Get agent budget',
description: "Get this agent token's spend budget, amount spent this window, and remaining USD.",
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { title: 'Get agent budget', ...READ },
},
{
name: 'get_portfolio',
title: 'Get portfolio',
description: 'Get the current crypto positions and daily P/L for the linked account.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { title: 'Get portfolio', ...READ },
},
{
name: 'get_quote',
title: 'Get quote',
description: 'Get the latest known price for a trading pair (e.g. BTC-USD).',
inputSchema: {
type: 'object',
properties: { pair: { type: 'string', description: 'Trading pair, e.g. BTC-USD' } },
required: ['pair'],
},
annotations: { title: 'Get quote', ...READ },
},
{
name: 'place_order',
title: 'Place crypto buy',
description: 'Place a crypto BUY for the given USD amount, hard-capped by the token budget. Returns accepted/queued; the engine re-checks risk + budget before execution.',
inputSchema: {
type: 'object',
Expand All @@ -47,14 +65,37 @@ const TOOLS = [
},
required: ['pair', 'usd'],
},
// Spends real money on an exchange: not read-only, not undoable, reaches outside b1dz.
annotations: { title: 'Place crypto buy', readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
},
] as const;

function rpcResult(id: unknown, result: unknown) {
return Response.json({ jsonrpc: '2.0', id, result });
return Response.json({ jsonrpc: '2.0', id, result }, { headers: CORS_HEADERS });
}
function rpcError(id: unknown, code: number, message: string, httpStatus = 200) {
return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status: httpStatus });
return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status: httpStatus, headers: CORS_HEADERS });
}

/** 401 + the RFC 9728 pointer; `invalid_token` when a credential was sent but did not resolve. */
function challenge(id: unknown, presented: boolean) {
const parts = [`Bearer resource_metadata="${resourceMetadataUrl()}"`, `scope="${SCOPE}"`];
if (presented) parts.push('error="invalid_token"', 'error_description="The access token is invalid or expired"');
return Response.json(
{ jsonrpc: '2.0', id, error: { code: -32001, message: 'unauthorized: sign in with OAuth or provide a valid b1dz_agent_ token' } },
{ status: 401, headers: { ...CORS_HEADERS, 'www-authenticate': parts.join(', '), 'cache-control': 'no-store' } },
);
}

function bearer(req: NextRequest): string | null {
const m = /^Bearer\s+(\S+)$/i.exec((req.headers.get('authorization') ?? '').trim());
return m ? m[1] : null;
}

/** OAuth access token or b1dz_agent_ key; both resolve to the same AuthedAgent shape. */
async function principal(req: NextRequest, token: string): Promise<AuthedAgent | null> {
if (token.startsWith(ACCESS_PREFIX)) return resolveAccessToken(createAdminSupabase(), token);
return authenticateAgent(req);
}
function toolText(payload: unknown, isError = false) {
return { content: [{ type: 'text', text: JSON.stringify(payload) }], isError };
Expand All @@ -78,28 +119,30 @@ async function runTool(agent: AuthedAgent, name: string, args: Record<string, un
}

export async function POST(req: NextRequest) {
const token = bearer(req);
const agent = token ? await principal(req, token) : null;
const msg = (await req.json().catch(() => null)) as { jsonrpc?: string; id?: unknown; method?: string; params?: Record<string, unknown> } | null;
if (!agent) return challenge(msg?.id ?? null, Boolean(token));
if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
return rpcError(msg?.id ?? null, -32600, 'invalid JSON-RPC request', 400);
}

// `initialize` and notifications don't require auth to negotiate; tool calls do.
if (msg.method === 'initialize') {
const asked = String(msg.params?.protocolVersion ?? '');
return rpcResult(msg.id, {
protocolVersion: PROTOCOL_VERSION,
capabilities: { tools: {} },
serverInfo: { name: 'b1dz-agent', version: '1.0.0' },
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
capabilities: { tools: { listChanged: false } },
serverInfo: { name: 'b1dz-agent', title: 'b1dz', version: '1.1.0' },
instructions:
'b1dz crypto trading for agents. get_budget, get_portfolio and get_quote are read-only. place_order queues a crypto BUY, hard-capped by this connection\'s budget; it fails when the connection has no trading budget.',
});
}
if (msg.method === 'notifications/initialized' || msg.method === 'ping') {
return msg.id === undefined ? new Response(null, { status: 202 }) : rpcResult(msg.id, {});
}

const agent = await authenticateAgent(req);
if (!agent) return rpcError(msg.id ?? null, -32001, 'unauthorized: provide a valid b1dz_agent_ token', 401);
if (msg.method.startsWith('notifications/')) return new Response(null, { status: 202, headers: CORS_HEADERS });
if (msg.method === 'ping') return rpcResult(msg.id, {});

if (msg.method === 'tools/list') {
return rpcResult(msg.id, { tools: TOOLS });
// resultType/ttlMs/cacheScope: required on list results by current MCP clients.
return rpcResult(msg.id, { tools: TOOLS, resultType: 'complete', ttlMs: 300_000, cacheScope: 'public' });
}
if (msg.method === 'tools/call') {
const name = String(msg.params?.name ?? '');
Expand All @@ -114,3 +157,15 @@ export async function POST(req: NextRequest) {

return rpcError(msg.id ?? null, -32601, `method not found: ${msg.method}`);
}

/** No server-to-client stream: 401 for anyone signed out (starts OAuth), 405 otherwise. */
export async function GET(req: NextRequest) {
const token = bearer(req);
const agent = token ? await principal(req, token) : null;
if (!agent) return challenge(null, Boolean(token));
return new Response(null, { status: 405, headers: { ...CORS_HEADERS, allow: 'POST, OPTIONS' } });
}

export function OPTIONS() {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
Loading
Loading