Skip to content

Commit 9e8b3bc

Browse files
author
Rajat
committed
Conformance with SendLit's implementation of MCP July 26 spec
1 parent 8181b4c commit 9e8b3bc

14 files changed

Lines changed: 164 additions & 396 deletions

File tree

‎apps/api/.env.example‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,6 @@ BETTER_AUTH_SECRET=
1111
# This app's own public origin. Falls back to http://localhost:4000.
1212
API_PUBLIC_URL=http://localhost:4000
1313

14-
# Comma-separated browser origins allowed to call /mcp. The API and WEB_CLIENT
15-
# origins are always included. Desktop/server clients normally send no Origin.
16-
# Add exact hosted playground/inspector origins when they call MCP from a
17-
# browser; wildcards are intentionally unsupported.
18-
MCP_ALLOWED_ORIGINS=
19-
2014
# Set to true only when the API is reached through exactly one trusted reverse
2115
# proxy hop (for example, a local Tailscale Funnel proxying to this process).
2216
# This lets Express and express-rate-limit use X-Forwarded-For correctly.

‎apps/api/docs/mcp-architecture.md‎

Lines changed: 41 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,7 @@ The MCP router is mounted before global CORS and Express body parsers in
8484
content-type checks, and MCP protocol errors. The route does not rewrite
8585
`Accept`; supported clients must send a protocol-valid header.
8686

87-
The MCP route validates every present `Origin` against the API origin, the
88-
configured `WEB_CLIENT` origin, and exact comma-separated
89-
`MCP_ALLOWED_ORIGINS`. An invalid Origin receives HTTP 403 before
90-
authentication. Requests without Origin remain valid for desktop and
91-
server-side clients. Wildcards are intentionally unsupported.
92-
93-
For an allowed browser origin, the MCP CORS contract permits:
87+
For a browser origin, the MCP CORS contract permits:
9488

9589
- methods `POST` and `OPTIONS`; and
9690
- `Content-Type`, `Accept`, `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`,
@@ -259,21 +253,18 @@ token exchange.
259253

260254
### Bearer-token verification
261255

262-
Bearer verification is implemented by the sibling
263-
`@codelitdev/oauth-server-kit`. With Better Auth 1.7 it must call:
256+
Bearer verification is implemented in `apps/api/src/auth/resolve-auth.ts`
257+
through Better Auth's resource client:
264258

265259
```ts
266260
oauthResourceClient.getActions().verifyBearerToken(...)
267261
```
268262

269-
Do not regress this to the removed `verifyAccessToken()` action. Verification
263+
Do not replace this with the published OAuth kit's legacy token-verification
264+
helper or regress it to the removed `verifyAccessToken()` action. Verification
270265
checks signature, issuer, expiry, and resource audience before FrontLit maps
271-
the subject to an account and tenant.
272-
273-
FrontLit currently consumes the kit through a local `file:` dependency. A
274-
deployment must use a built/published kit containing the Better Auth 1.7
275-
verifier; an older installed package can make a freshly issued JWT fail as
276-
`invalid_token`.
266+
the subject to an account and tenant. This matches SendLit's Better Auth 1.7
267+
integration.
277268

278269
## Tool authorization
279270

@@ -316,10 +307,8 @@ OAuth calls must contain the policy's required scope. Read scopes do not grant
316307
writes, and `send_broadcast` specifically requires `broadcasts:send`.
317308

318309
Unauthenticated and invalid-token responses include a Bearer challenge with
319-
the protected-resource metadata URL and supported MCP scopes. For modern tool
320-
calls, the `Mcp-Name` header allows the route to return HTTP 403 with an
321-
`insufficient_scope` challenge naming the required scope. The tool-level
322-
policy remains in place for older requests and as defense in depth.
310+
the protected-resource metadata URL. Missing OAuth scopes are rejected by the
311+
tool-level policy for both supported protocol eras.
323312

324313
Team API keys do not currently have per-scope grants and preserve their
325314
existing fixed-team access. Account-only tools reject API-key authentication.
@@ -387,15 +376,6 @@ This configures Express with one trusted hop so `express-rate-limit` can use
387376
`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR` or trust an arbitrary proxy chain; fix the
388377
deployment topology/configuration.
389378

390-
For browser-hosted clients outside the API and web-app origins, configure:
391-
392-
```dotenv
393-
MCP_ALLOWED_ORIGINS=https://playground.example.com,https://inspector.example.com
394-
```
395-
396-
Each value must be an exact HTTP(S) origin without a path, query, credentials,
397-
or fragment. Production values must use HTTPS.
398-
399379
Request and tool logs include method/tool, auth kind, required scope, policy
400380
decision, outcome, status, and duration where available. They must not include
401381
bearer tokens, API-key secrets, authorization codes, OTPs, CIMD bodies, or tool
@@ -463,7 +443,7 @@ flow, and JWT claims.
463443
| `apps/api/src/db/auth-schema.ts` | FrontLit model names for Better Auth/OAuth persistence |
464444
| `apps/api/drizzle/0004_*`, `0005_*` | Additive Better Auth 1.7 database changes |
465445
| `apps/docs/content/docs/developers/mcp.mdx` | User-facing connection and troubleshooting guide |
466-
| `@codelitdev/oauth-server-kit` sibling | Shared discovery, hosted OAuth helpers, and Better Auth bearer verification |
446+
| `@codelitdev/oauth-server-kit` | Shared discovery, hosted OAuth helpers, and neutral auth types |
467447

468448
## Dependencies
469449

@@ -592,57 +572,56 @@ OAuth metadata, scopes, team membership, or the tool catalog.
592572

593573
Diagnose the first failing layer rather than the last error a client displays.
594574

595-
| Symptom | Likely cause and action |
596-
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
597-
| Public URL times out | Check local `/health`, Funnel/tunnel process, listener target, public DNS, and TLS before inspecting MCP code. |
598-
| `ERR_ERL_UNEXPECTED_X_FORWARDED_FOR` | Set `ENABLE_TRUST_PROXY=true` only for the intended one-hop proxy deployment. |
599-
| `auth_oauth_resource` does not exist | Apply migration `0004` before starting Better Auth. |
600-
| JWKS schema says `alg` is missing | Apply migration `0005` and confirm deployed schema/code alignment. |
601-
| `invalid_client` fetching a metadata URL | Check HTTPS, public DNS resolution, fetch timeout/size policy, redirect behavior, and the exact client metadata URL. |
602-
| `invalid_client_metadata` for Device Code or JWT Bearer | Confirm the request uses the canonical VS Code or Claude metadata URL and the exact grant filter is active. Do not add a global filter. |
603-
| Browser OAuth succeeds, then `/mcp` returns `invalid_token` | Confirm the installed OAuth kit calls Better Auth 1.7 `verifyBearerToken()` and validates the exact public MCP audience. Clear stale client tokens after deploying the fix. |
604-
| OAuth client remains “Authenticating” | Inspect token exchange and the first authenticated `POST /mcp`; browser callback success alone does not prove token issuance or MCP initialization. |
605-
| Client reports `404 Cannot GET /mcp` after a `400`, `401`, or `409` POST | The GET is an expected SSE fallback and secondary symptom. Keep GET as 404 and fix the earlier POST. |
606-
| Consent lists every MCP scope | This can be the registered client capability set. Verify the requested scope, issued token scope, and per-tool enforcement before treating it as an over-grant. |
607-
| Client shows generic failure for a new user | Confirm the user belongs to a FrontLit team and that the no-team page appears before consent. |
608-
| Single-team token lacks `team_id` | Confirm the sole-team path returns that team's ID as the consent `reference_id`. |
609-
| Tool mutation succeeds but client reports output validation failure | Inspect `structuredContent` for unnormalized `Date` values and ensure the result went through `jsonResult()`. |
610-
| VS Code works but Inspector or Claude fails | Test protocol era and OAuth onboarding separately: older Streamable HTTP, modern 2026, CIMD, and DCR are independent compatibility axes. |
575+
| Symptom | Likely cause and action |
576+
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
577+
| Public URL times out | Check local `/health`, Funnel/tunnel process, listener target, public DNS, and TLS before inspecting MCP code. |
578+
| `ERR_ERL_UNEXPECTED_X_FORWARDED_FOR` | Set `ENABLE_TRUST_PROXY=true` only for the intended one-hop proxy deployment. |
579+
| `auth_oauth_resource` does not exist | Apply migration `0004` before starting Better Auth. |
580+
| JWKS schema says `alg` is missing | Apply migration `0005` and confirm deployed schema/code alignment. |
581+
| `invalid_client` fetching a metadata URL | Check HTTPS, public DNS resolution, fetch timeout/size policy, redirect behavior, and the exact client metadata URL. |
582+
| `invalid_client_metadata` for Device Code or JWT Bearer | Confirm the request uses the canonical VS Code or Claude metadata URL and the exact grant filter is active. Do not add a global filter. |
583+
| Browser OAuth succeeds, then `/mcp` returns `invalid_token` | Confirm `resolve-auth.ts` calls Better Auth 1.7 `verifyBearerToken()` and validates the exact public MCP audience. Clear stale client tokens after deploying the fix. |
584+
| OAuth client remains “Authenticating” | Inspect token exchange and the first authenticated `POST /mcp`; browser callback success alone does not prove token issuance or MCP initialization. |
585+
| Client reports `404 Cannot GET /mcp` after a `400`, `401`, or `409` POST | The GET is an expected SSE fallback and secondary symptom. Keep GET as 404 and fix the earlier POST. |
586+
| Consent lists every MCP scope | This can be the registered client capability set. Verify the requested scope, issued token scope, and per-tool enforcement before treating it as an over-grant. |
587+
| Client shows generic failure for a new user | Confirm the user belongs to a FrontLit team and that the no-team page appears before consent. |
588+
| Single-team token lacks `team_id` | Confirm the sole-team path returns that team's ID as the consent `reference_id`. |
589+
| Tool mutation succeeds but client reports output validation failure | Inspect `structuredContent` for unnormalized `Date` values and ensure the result went through `jsonResult()`. |
590+
| VS Code works but Inspector or Claude fails | Test protocol era and OAuth onboarding separately: older Streamable HTTP, modern 2026, CIMD, and DCR are independent compatibility axes. |
611591

612592
## Maintenance rules for future changes
613593

614594
1. Keep one SDK 2 handler with `legacy: "stateless"`; do not add an SDK 1 or
615595
standalone SSE server.
616596
2. Keep `/mcp` before Express body parsing and global CORS.
617-
3. Validate every present browser Origin against the explicit MCP allowlist.
618-
4. Build a request-local server and store no protocol session state in memory.
619-
5. Add every new tool to `policy.ts`; the exact catalog/policy test must pass.
620-
6. Add new scopes to the shared scope constants so policy, OAuth metadata,
597+
3. Build a request-local server and store no protocol session state in memory.
598+
4. Add every new tool to `policy.ts`; the exact catalog/policy test must pass.
599+
5. Add new scopes to the shared scope constants so policy, OAuth metadata,
621600
resource registration, and tests remain aligned.
622-
7. Treat OAuth client ID, account ID, team ID, and credentials as distinct
601+
6. Treat OAuth client ID, account ID, team ID, and credentials as distinct
623602
values.
624-
8. Never place raw API-key secrets or sensitive OAuth URL data in context or
603+
7. Never place raw API-key secrets or sensitive OAuth URL data in context or
625604
logs.
626-
9. Keep OAuth registration defaults identity-only and require explicit
605+
8. Keep OAuth registration defaults identity-only and require explicit
627606
authorization scopes.
628-
10. Keep arbitrary CIMD URLs behind the pinned public-network fetch policy;
629-
add client exceptions only for exact canonical URLs and exact fields.
630-
11. Keep REST schemas canonical on Zod 3 until a separate repository-wide
607+
9. Keep arbitrary CIMD URLs behind the pinned public-network fetch policy;
608+
add client exceptions only for exact canonical URLs and exact fields.
609+
10. Keep REST schemas canonical on Zod 3 until a separate repository-wide
631610
migration is approved; bridge only at the MCP boundary.
632-
12. Route every structured result through `jsonResult()` so SDK output
611+
11. Route every structured result through `jsonResult()` so SDK output
633612
validation sees JSON values.
634-
13. Add Better Auth schema changes as new Drizzle migrations and test both
613+
12. Add Better Auth schema changes as new Drizzle migrations and test both
635614
fresh and upgrade paths; do not rewrite unrelated migration history.
636-
14. Re-run the shared OAuth kit integration tests after Better Auth upgrades.
637-
15. Diagnose the first failing MCP POST before reacting to a client's later
615+
13. Re-run the shared OAuth kit integration tests after Better Auth upgrades.
616+
14. Diagnose the first failing MCP POST before reacting to a client's later
638617
SSE fallback error.
639618

640619
## Last verified state
641620

642-
On 2026-08-10, after the July 2026 conformance audit:
621+
On 2026-08-10, after the July 2026 migration:
643622

644623
- FrontLit API type-check passed;
645-
- all 228 FrontLit API tests passed;
624+
- all 226 FrontLit API tests passed;
646625
- the FrontLit API production build passed;
647626
- repository ESLint passed;
648627
- the documentation production build passed;

‎apps/api/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"@ai-sdk/openai-compatible": "^3.0.16",
2323
"@better-auth/cimd": "1.7.0-rc.4",
2424
"@better-auth/oauth-provider": "1.7.0-rc.4",
25-
"@codelitdev/oauth-server-kit": "file:../../../oauth-server-kit",
25+
"@codelitdev/oauth-server-kit": "0.1.0-alpha.0",
2626
"@frontlit/api-contract": "workspace:*",
2727
"@modelcontextprotocol/node": "^2.0.0",
2828
"@modelcontextprotocol/server": "^2.0.0",

‎apps/api/src/auth/better-auth.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ export const auth = betterAuth({
243243
allowDynamicClientRegistration: true,
244244
allowUnauthenticatedDynamicClientRegistration: true,
245245
scopes: supportedOAuthScopes,
246+
validAudiences: validOAuthAudiences,
246247
clientRegistrationDefaultScopes: OAUTH_CLIENT_DEFAULT_SCOPES,
247248
clientRegistrationAllowedScopes:
248249
OAUTH_CLIENT_REQUESTABLE_SCOPES,

‎apps/api/src/auth/middleware.test.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import { createAuthMiddleware } from "./middleware.js";
1313
async function requestFor(
1414
result: AuthResult | Error,
1515
resourceMetadataUrl?: string,
16-
challengeScopes: readonly string[] = [],
1716
) {
1817
const resolver = vi.fn(async () => {
1918
if (result instanceof Error) throw result;
@@ -22,12 +21,7 @@ async function requestFor(
2221
const app = express();
2322
app.get(
2423
"/protected",
25-
createAuthMiddleware(
26-
"mcp",
27-
resolver,
28-
resourceMetadataUrl,
29-
challengeScopes,
30-
),
24+
createAuthMiddleware("mcp", resolver, resourceMetadataUrl),
3125
(request, response) => {
3226
const productRequest = request as any;
3327
response.json({
@@ -162,11 +156,10 @@ describe("FrontLit auth middleware projection", () => {
162156
const { response } = await requestFor(
163157
{ status: "missing" },
164158
metadataUrl,
165-
["pages:read", "pages:write"],
166159
);
167160
expect(response.status).toBe(401);
168161
expect(response.headers.get("www-authenticate")).toBe(
169-
`Bearer resource_metadata="${metadataUrl}", scope="pages:read pages:write"`,
162+
`Bearer resource_metadata="${metadataUrl}"`,
170163
);
171164
});
172165

‎apps/api/src/auth/middleware.ts‎

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ import {
44
type AuthResult,
55
resolveAuth,
66
sendAuthError,
7-
setBearerChallenge,
87
} from "./resolve-auth";
9-
import { MCP_SCOPES_SUPPORTED } from "../mcp/policy";
108
import { mcpProtectedResourceMetadataUrl } from "./better-auth";
119

1210
type AuthResolver = (input: AuthInput) => Promise<AuthResult>;
@@ -15,7 +13,6 @@ export function createAuthMiddleware(
1513
mode: "rest" | "mcp",
1614
authResolver: AuthResolver = resolveAuth,
1715
resourceMetadataUrl?: string,
18-
challengeScopes: readonly string[] = [],
1916
) {
2017
return async function frontLitAuthMiddleware(
2118
request: Request,
@@ -29,23 +26,14 @@ export function createAuthMiddleware(
2926
bodyApiKey: request.body?.apikey,
3027
headers: request.headers,
3128
});
32-
if (
33-
sendAuthError(
34-
response,
35-
result,
36-
resourceMetadataUrl,
37-
challengeScopes,
38-
)
39-
)
40-
return;
29+
if (sendAuthError(response, result, resourceMetadataUrl)) return;
4130
if (result.status !== "authenticated") return;
4231

4332
if (mode === "mcp" && result.kind === "session") {
4433
if (resourceMetadataUrl) {
45-
setBearerChallenge(
46-
response,
47-
resourceMetadataUrl,
48-
challengeScopes,
34+
response.setHeader(
35+
"WWW-Authenticate",
36+
`Bearer resource_metadata="${resourceMetadataUrl}"`,
4937
);
5038
}
5139
response.status(401).json({
@@ -86,5 +74,4 @@ export const mcpAuth = createAuthMiddleware(
8674
"mcp",
8775
resolveAuth,
8876
mcpProtectedResourceMetadataUrl,
89-
MCP_SCOPES_SUPPORTED,
9077
);

0 commit comments

Comments
 (0)