@lostgradient/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -0
  3. package/dist/chunk-mf3t0afg.js +4 -0
  4. package/dist/chunk-psnez3q2.js +111 -0
  5. package/dist/chunk-taxyscge.js +67 -0
  6. package/dist/chunk-v14p4gng.js +25 -0
  7. package/dist/chunk-wmkqd45r.js +14 -0
  8. package/dist/conformance-fixture-registration.d.ts +30 -0
  9. package/dist/conformance-server.d.ts +1 -0
  10. package/dist/env.d.ts +59 -0
  11. package/dist/env.js +9 -0
  12. package/dist/environment-schema.d.ts +29 -0
  13. package/dist/environment-schema.js +6 -0
  14. package/dist/golden-prompts.d.ts +42 -0
  15. package/dist/handler-context.d.ts +16 -0
  16. package/dist/index.d.ts +25 -0
  17. package/dist/index.js +1326 -0
  18. package/dist/localhost-request-validation.d.ts +2 -0
  19. package/dist/logger.d.ts +39 -0
  20. package/dist/logger.js +14 -0
  21. package/dist/long-running-operation-support.d.ts +34 -0
  22. package/dist/metrics.d.ts +64 -0
  23. package/dist/metrics.js +6 -0
  24. package/dist/prompts/index.d.ts +5 -0
  25. package/dist/prompts/summarize.d.ts +4 -0
  26. package/dist/resources/index.d.ts +4 -0
  27. package/dist/resources/user-profile.d.ts +1 -0
  28. package/dist/scope-vocabulary.d.ts +127 -0
  29. package/dist/scopes.d.ts +49 -0
  30. package/dist/server.d.ts +113 -0
  31. package/dist/supported-scopes.d.ts +25 -0
  32. package/dist/template-registry.d.ts +16 -0
  33. package/dist/tool-response.d.ts +94 -0
  34. package/dist/tools/get-user-profile.d.ts +8 -0
  35. package/dist/tools/index.d.ts +16 -0
  36. package/dist/tools/list-audit-events.d.ts +11 -0
  37. package/dist/type-assertions.d.ts +1 -0
  38. package/dist/types/primitives.d.ts +130 -0
  39. package/dist/ui-extension-support.d.ts +20 -0
  40. package/dist/version.d.ts +23 -0
  41. package/dist/version.js +6 -0
  42. package/package.json +73 -0
@@ -0,0 +1,2 @@
1
+ export declare function isLoopbackHostname(hostname: string): boolean;
2
+ export declare function hasValidLocalhostRebindingHeaders(headers: Headers): boolean;
@@ -0,0 +1,39 @@
1
+ import pino from 'pino';
2
+ import type { DestinationStream } from 'pino';
3
+ /**
4
+ * OBS-001 / S-14: `logger.ts` previously declared no redaction paths at
5
+ * all, so any structured field that happened to carry a credential-shaped
6
+ * value would be written verbatim. This template's request boundary
7
+ * legitimately handles OAuth authorization codes, PKCE verifiers, access
8
+ * and refresh tokens, ID tokens, client secrets, session cookies, database
9
+ * and Redis connection strings (which embed credentials in the URL itself),
10
+ * and user email addresses — every one of those has a named path here.
11
+ *
12
+ * Pino's `redact.paths` (backed by `fast-redact`) matches by KEY, not by
13
+ * value, and its wildcard (`*`) only spans a single object level — there is
14
+ * no recursive `**`. So paths are enumerated at the depths this codebase
15
+ * actually logs at: top-level (a call site logs `{ token, ... }` directly),
16
+ * one level nested (`{ headers: { authorization } }`,
17
+ * `{ client: { client_secret } }`), and the specific two-level `headers.*`
18
+ * shape a request-logging call site would use. A secret landing at some
19
+ * other, unanticipated depth is not caught by key-path redaction — that gap
20
+ * is exactly what `redactSecretValues` below (wired through pino's
21
+ * `hooks.streamWrite`) exists to catch by VALUE instead, and
22
+ * `redaction.test.ts` proves both mechanisms against a real, unmocked
23
+ * logger rather than trusting this list is complete.
24
+ */
25
+ export declare const redactionPaths: readonly string[];
26
+ /**
27
+ * A factory, not just a singleton export, so tests can build a real logger
28
+ * — the actual redaction config below, not a copy of it — against an
29
+ * in-memory destination instead of stdout. Passing `destination` also
30
+ * forces plain JSON output (no `pino-pretty` transport): pino refuses to
31
+ * combine `options.transport` with a destination stream argument, and
32
+ * tests need to parse exactly what was written, not a human-formatted
33
+ * approximation of it.
34
+ */
35
+ export declare function createLogger(options?: {
36
+ destination?: DestinationStream;
37
+ }): pino.Logger;
38
+ export declare function getLogger(): pino.Logger;
39
+ export declare const logger: pino.Logger;
package/dist/logger.js ADDED
@@ -0,0 +1,14 @@
1
+ import {
2
+ createLogger,
3
+ getLogger,
4
+ logger,
5
+ redactionPaths
6
+ } from "./chunk-psnez3q2.js";
7
+ import"./chunk-v14p4gng.js";
8
+ import"./chunk-wmkqd45r.js";
9
+ export {
10
+ createLogger,
11
+ getLogger,
12
+ logger,
13
+ redactionPaths
14
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * SEC-004: "a timeout must abort the underlying operation rather than
3
+ * merely reject a wrapper promise." The previous implementation raced
4
+ * `operation()` against a timer with `Promise.race` — once the timer won,
5
+ * the wrapper promise rejected, but `operation()` itself kept running with
6
+ * nothing left to observe it: no caller awaiting its result, no signal
7
+ * telling it to stop, and no way to know its eventual resolution (or
8
+ * rejection, which becomes an unhandled rejection) was ever handled. For a
9
+ * fetch, a database query, or any operation that accepts a signal, that
10
+ * means the timeout only stopped *waiting* — it never stopped the work.
11
+ *
12
+ * This still races against a timer, so a caller is guaranteed a result (or
13
+ * rejection) by the deadline even if `operation` ignores cancellation
14
+ * entirely. What's new: `operation` now receives the `AbortSignal` this
15
+ * function creates and aborts on timeout (or on the caller's own
16
+ * `abortSignal` firing), so a caller that threads it into
17
+ * `fetch`/a query/etc. gets genuine cancellation of the underlying work,
18
+ * not just an abandoned promise racing in the background.
19
+ */
20
+ export declare function runWithStandardizedTimeout<T>(input: {
21
+ operation: (signal: AbortSignal) => Promise<T>;
22
+ timeoutMilliseconds?: number;
23
+ abortSignal?: AbortSignal;
24
+ }): Promise<T>;
25
+ export declare function emitRequestProgress(input: {
26
+ sendNotification?: (notification: {
27
+ method: string;
28
+ params: Record<string, unknown>;
29
+ }) => Promise<void>;
30
+ progressToken?: string | number;
31
+ progress: number;
32
+ total?: number;
33
+ message?: string;
34
+ }): Promise<void>;
@@ -0,0 +1,64 @@
1
+ export type ToolMetricEntry = {
2
+ invocations: number;
3
+ errors: number;
4
+ durations: number[];
5
+ };
6
+ /**
7
+ * OBS-001: outcome counters for the OAuth and MCP surfaces the roadmap
8
+ * names — discovery, authorization, token exchange, refresh, revocation,
9
+ * registration, MCP method dispatch, stream disconnects, version
10
+ * negotiation, and conformance failures. Deliberately a flat
11
+ * `category -> outcome -> count` map rather than one field per category:
12
+ * every category has the same shape (a set of named, mutually exclusive
13
+ * outcomes), and this lets a new outcome or category be added at a call
14
+ * site with no change here. `tools` above stays its own typed field
15
+ * because it also carries latency percentiles, which events do not.
16
+ */
17
+ export type EventOutcomeCounts = Record<string, Record<string, number>>;
18
+ export type MetricsSnapshot = {
19
+ tools: Record<string, {
20
+ invocations: number;
21
+ errors: number;
22
+ p50: number;
23
+ p95: number;
24
+ p99: number;
25
+ }>;
26
+ events: EventOutcomeCounts;
27
+ uptimeSeconds: number;
28
+ collectedAt: string;
29
+ };
30
+ declare class MetricsCollector {
31
+ private tools;
32
+ private events;
33
+ private startedAt;
34
+ recordToolInvocation(name: string, durationMs: number, isError: boolean): void;
35
+ /**
36
+ * OBS-001: increments the counter for one `(category, outcome)` pair —
37
+ * e.g. `recordEvent('registration', 'success')`,
38
+ * `recordEvent('token_exchange', 'invalid_client')`,
39
+ * `recordEvent('authorization', 'user_denied')`. Never pass a secret,
40
+ * token, or user-identifying value as `outcome` — this is a metric
41
+ * label, not a log field, and stays in memory for the life of the
42
+ * process.
43
+ */
44
+ recordEvent(category: string, outcome: string): void;
45
+ /**
46
+ * Review round 4 / P2: this previously cleared `entry.durations` after
47
+ * computing percentiles, on the mistaken assumption that a snapshot is a
48
+ * one-shot read. `/metrics` (`metrics-routes.ts`) is a Prometheus-style
49
+ * scrape endpoint -- polled repeatedly by one or more scrapers -- and a
50
+ * scrape must be idempotent: reading it must never change what the next
51
+ * reader sees. Clearing the samples here meant a second scraper, or the
52
+ * same scraper on its next interval before another tool invocation, saw
53
+ * `p50`/`p95`/`p99` reset to `0` while `invocations`/`errors` kept
54
+ * climbing -- an internally inconsistent snapshot, and one reader
55
+ * silently consuming data before another could see it. The bounded
56
+ * last-`MAX_DURATIONS` window in `recordToolInvocation` already keeps
57
+ * memory bounded, so nothing here needs to clear it -- the window
58
+ * naturally ages out old samples as new ones arrive.
59
+ */
60
+ snapshot(): MetricsSnapshot;
61
+ reset(): void;
62
+ }
63
+ export declare const metricsCollector: MetricsCollector;
64
+ export {};
@@ -0,0 +1,6 @@
1
+ import {
2
+ metricsCollector
3
+ } from "./chunk-taxyscge.js";
4
+ export {
5
+ metricsCollector
6
+ };
@@ -0,0 +1,5 @@
1
+ import type { z } from 'zod';
2
+ import type { McpPromptDefinition } from '../types/primitives.js';
3
+ import type { McpScope } from '../scopes.js';
4
+ export { summarizePrompt } from './summarize.js';
5
+ export declare const allPrompts: McpPromptDefinition<Record<string, z.ZodType> | undefined, McpScope>[];
@@ -0,0 +1,4 @@
1
+ import { z } from 'zod';
2
+ export declare const summarizePrompt: import("../index.js").McpPromptDefinition<{
3
+ topic: z.ZodString;
4
+ }, "profile:read" | "audit:read" | "prompts:read">;
@@ -0,0 +1,4 @@
1
+ import type { McpResourceDefinition } from '../types/primitives.js';
2
+ import type { McpScope } from '../scopes.js';
3
+ export { userProfileResource } from './user-profile.js';
4
+ export declare const allResources: McpResourceDefinition<McpScope>[];
@@ -0,0 +1 @@
1
+ export declare const userProfileResource: import("../index.js").McpResourceDefinition<"profile:read" | "audit:read" | "prompts:read">;
@@ -0,0 +1,127 @@
1
+ import type { z } from 'zod';
2
+ import type { McpPromptDefinition, McpResourceDefinition, McpToolDefinition } from './types/primitives.js';
3
+ /**
4
+ * AUTHZ-001: a consumer's OAuth scope vocabulary, closed per consumer rather
5
+ * than closed to one set globally. The properties the original fixed
6
+ * vocabulary carried are the ones that have to survive being opened:
7
+ *
8
+ * - Every primitive declares **exactly one** scope from this set. Opening the
9
+ * vocabulary must not open that, so `requiredScope` stays a single value of
10
+ * `Scope` — never an array, never optional.
11
+ * - There is no generic all-access scope, and none can be expressed. The
12
+ * authorization check is exact membership (`grantedScopes.includes(...)`),
13
+ * so a token granted `'*'` authorizes nothing. Widening happens only on the
14
+ * declaration side; the granted side stays `readonly string[]`.
15
+ * - Conformance-only scopes are excluded from `getSupportedScopes()`
16
+ * structurally, by walking the production registries alone, not by a second
17
+ * exclusion list somebody has to remember to update.
18
+ */
19
+ export type McpScopeVocabulary<Scope extends string> = {
20
+ /** Every scope in the vocabulary, in declaration order. */
21
+ readonly scopes: readonly Scope[];
22
+ /** Consent-screen text, shown verbatim on the authorize page. */
23
+ readonly descriptions: Readonly<Record<Scope, string>>;
24
+ /** Narrowing check against this vocabulary rather than a fixed list. */
25
+ isScope(value: string): value is Scope;
26
+ /**
27
+ * Definers bound to this vocabulary. Using these rather than the bare
28
+ * ones from `types/primitives.js` is what puts a mistyped scope on the
29
+ * primitive's own line: an unbound `defineTool` infers `Scope` from
30
+ * whatever literal it is given, so `'reposotories:read'` type-checks
31
+ * there and only fails later at registry assignment, far from the
32
+ * mistake. Same reasoning as `META-001` requiring `title` and
33
+ * `annotations` — a compile error on the file you are editing beats one
34
+ * a reviewer has to trace.
35
+ */
36
+ defineTool<InputSchema extends z.ZodType, OutputSchema extends z.ZodType | undefined = undefined>(definition: McpToolDefinition<InputSchema, OutputSchema, Scope>): McpToolDefinition<InputSchema, OutputSchema, Scope>;
37
+ defineResource(definition: McpResourceDefinition<Scope>): McpResourceDefinition<Scope>;
38
+ definePrompt<Arguments extends Record<string, z.ZodType> | undefined>(definition: McpPromptDefinition<Arguments, Scope>): McpPromptDefinition<Arguments, Scope>;
39
+ /**
40
+ * Builds a registry pinned to this vocabulary.
41
+ *
42
+ * Use this rather than writing an object literal and letting `McpRegistry`
43
+ * default `Scope` to `string`. An inferred registry accepts a primitive
44
+ * from an unbound definer or from a *different* vocabulary with no type
45
+ * error, and `getSupportedScopes()` then advertises a scope this
46
+ * vocabulary has no description for and whose `isScope()` returns false —
47
+ * so the authorization layer cannot issue the scope the served primitive
48
+ * requires. Annotating the registry by hand also prevents that, but only
49
+ * if the author remembers to; this makes the binding the default path.
50
+ */
51
+ defineRegistry(registry: McpRegistry<Scope>): McpRegistry<Scope>;
52
+ };
53
+ /**
54
+ * The scope names a descriptions object actually yields at runtime.
55
+ *
56
+ * `Object.keys()` stringifies every key, so `{ 123: '...' }` produces the
57
+ * scope `'123'`. Taking only `Extract<keyof D, string>` would discard that
58
+ * numeric literal and type the vocabulary as `McpScopeVocabulary<never>` —
59
+ * its bound definers would reject `requiredScope: '123'` even though
60
+ * `isScope('123')` returns true at runtime. Templating the numeric keys back
61
+ * to strings keeps the type and the runtime describing the same set.
62
+ */
63
+ type ScopeOf<Descriptions> = Extract<keyof Descriptions, string> | `${Extract<keyof Descriptions, number>}`;
64
+ export declare function defineScopes<const Descriptions extends Record<string, string> & {
65
+ /**
66
+ * `__proto__` cannot be a scope name, and this rejects it where it is
67
+ * written rather than letting it vanish. In an object literal the key
68
+ * is special: it never becomes an own property, so `Object.keys()`
69
+ * would return nothing while TypeScript still infers it as a member of
70
+ * `Scope`. The bound definers would then accept primitives requiring a
71
+ * scope that `scopes` omits and `isScope()` rejects — unauthorizable,
72
+ * with no error anywhere. No runtime read can recover the key, so the
73
+ * type is the only place this can be caught.
74
+ */
75
+ __proto__?: never;
76
+ }>(descriptions: Descriptions): McpScopeVocabulary<ScopeOf<Descriptions>>;
77
+ /**
78
+ * The primitives a server serves, supplied by whoever is building it.
79
+ *
80
+ * `conformanceOnlyTools` is separate rather than a flag on a tool because the
81
+ * separation is what `getSupportedScopes()` reads: it walks the production
82
+ * three and never this one, so a scope declared only by a conformance fixture
83
+ * cannot reach a real OAuth client. Collapsing them into one list with a
84
+ * boolean would move that guarantee from the shape of the data into a filter
85
+ * somebody can forget.
86
+ *
87
+ * Note there is no conformance-only slot for resources or prompts, and that
88
+ * is not an oversight: the protocol conformance fixtures registered by
89
+ * `registerConformanceFixtures()` are imperative and declare no
90
+ * `requiredScope`, so they never participate in the scope vocabulary at all.
91
+ */
92
+ export type McpRegistry<Scope extends string = string> = {
93
+ /**
94
+ * Natural-language server instructions, handed to the MCP client and fed
95
+ * straight to a model. Optional only so this repository's own registry can
96
+ * keep using the bundled `instructions.md`; **a consumer should always set
97
+ * it.**
98
+ *
99
+ * Serving one registry's instructions alongside another's primitives is
100
+ * worse than unhelpful. The bundled text names `get_user_profile`,
101
+ * `user://profile`, and `summarize`, points at this template's OAuth
102
+ * endpoints, and states that no operation is destructive. A consumer that
103
+ * inherits it hands a model a description of tools that do not exist — and,
104
+ * far more seriously, an assurance that its own mutating tools are
105
+ * read-only.
106
+ */
107
+ readonly instructions?: string;
108
+ /**
109
+ * The implementation identity reported in the `initialize` response.
110
+ *
111
+ * Optional only so this repository's own registry keeps deriving its name
112
+ * from `MCP_SERVER_NAME`; **a consumer should always set it.** Without it a
113
+ * consumer's server reports this package's name and version, so clients and
114
+ * operators misattribute it in diagnostics, and any client behaviour keyed
115
+ * to `serverInfo` — compatibility shims, version gates — reads the wrong
116
+ * implementation entirely.
117
+ */
118
+ readonly serverInfo?: {
119
+ readonly name: string;
120
+ readonly version: string;
121
+ };
122
+ readonly tools: readonly McpToolDefinition<z.ZodType, z.ZodType | undefined, Scope>[];
123
+ readonly resources: readonly McpResourceDefinition<Scope>[];
124
+ readonly prompts: readonly McpPromptDefinition<Record<string, z.ZodType> | undefined, Scope>[];
125
+ readonly conformanceOnlyTools?: readonly McpToolDefinition<z.ZodType, z.ZodType | undefined, Scope>[];
126
+ };
127
+ export {};
@@ -0,0 +1,49 @@
1
+ /**
2
+ * AUTHZ-001: this server's own OAuth scope vocabulary. It is now one
3
+ * vocabulary among possibly several — `scope-vocabulary.ts` holds the
4
+ * mechanism, and records which properties had to survive being opened to
5
+ * consumers — but the reasoning behind these three is unchanged.
6
+ *
7
+ * The set is deliberately small and drawn straight from what the production
8
+ * registries actually do; a "generic all-access scope" is exactly what the
9
+ * roadmap says not to build. Every tool, resource, and prompt declares a
10
+ * `requiredScope` from this set (`McpToolDefinition`/`McpResourceDefinition`/
11
+ * `McpPromptDefinition` in `types/primitives.ts`), which is what turns "a
12
+ * scope exists" into "every operation is gated by one."
13
+ *
14
+ * `audit:read` gates `list_audit_events`, a conformance-only fixture
15
+ * (`CONTENT-001`/`META-001`) that is never registered in a production
16
+ * deployment. It stays in the vocabulary — the tool still needs a real
17
+ * `requiredScope` to satisfy the metadata contract and to be enforceable at
18
+ * all when conformance mode is on — but `getSupportedScopes()` deliberately
19
+ * excludes it from what a real OAuth client can ever request or see
20
+ * advertised, because advertising a scope that only unlocks a fixture no
21
+ * production deployment serves is exactly the "claims a capability it does
22
+ * not implement" overclaiming this branch (`S-20`) exists to remove.
23
+ *
24
+ * The strings below are the consent-screen-facing descriptions, shown
25
+ * verbatim on the authorize page so "the exact requested scopes" (the
26
+ * roadmap's own phrase) is something a user can read rather than a raw
27
+ * token. They are also what *declares* the vocabulary — a scope with no
28
+ * description cannot be written here at all.
29
+ */
30
+ export declare const templateScopeVocabulary: import("./scope-vocabulary.js").McpScopeVocabulary<"profile:read" | "audit:read" | "prompts:read">;
31
+ export type McpScope = (typeof templateScopeVocabulary.scopes)[number];
32
+ /**
33
+ * The three exports below keep the exact shape every existing caller already
34
+ * imports — `applications/web`'s authorize page renders
35
+ * `mcpScopeDescriptions`, `oauth-scope.ts` narrows with `isMcpScope`, and
36
+ * `request-limits.ts` sizes a bound against `mcpScopes`. Opening the
37
+ * vocabulary changed how these are derived, not what they are.
38
+ */
39
+ export declare const mcpScopes: readonly McpScope[];
40
+ export declare const mcpScopeDescriptions: Readonly<Record<McpScope, string>>;
41
+ export declare function isMcpScope(value: string): value is McpScope;
42
+ /**
43
+ * Definers bound to this server's own vocabulary. The primitive files import
44
+ * these rather than the unbound helpers in `types/primitives.js`, so a
45
+ * mistyped scope fails on the primitive's own line — the same protection a
46
+ * consumer gets from its own `defineScopes()` call, and the same philosophy
47
+ * as `META-001` requiring `title` and `annotations` up front.
48
+ */
49
+ export declare const defineTool: <InputSchema extends import("zod").ZodType, OutputSchema extends import("zod").ZodType | undefined = undefined>(definition: import("./index.js").McpToolDefinition<InputSchema, OutputSchema, "profile:read" | "audit:read" | "prompts:read">) => import("./index.js").McpToolDefinition<InputSchema, OutputSchema, "profile:read" | "audit:read" | "prompts:read">, defineResource: (definition: import("./index.js").McpResourceDefinition<"profile:read" | "audit:read" | "prompts:read">) => import("./index.js").McpResourceDefinition<"profile:read" | "audit:read" | "prompts:read">, definePrompt: <Arguments extends Record<string, import("zod").ZodType> | undefined>(definition: import("./index.js").McpPromptDefinition<Arguments, "profile:read" | "audit:read" | "prompts:read">) => import("./index.js").McpPromptDefinition<Arguments, "profile:read" | "audit:read" | "prompts:read">;
@@ -0,0 +1,113 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import type { McpUserProfile } from './types/primitives.js';
3
+ import type { McpRegistry } from './scope-vocabulary.js';
4
+ /**
5
+ * Round-seventeen review (P2): `resources/read` rejects an under-scoped
6
+ * request via `assertRequiredScope` before the handler ever runs, but the
7
+ * `2026-07-28` `subscriptions/listen` stream (the push-notification path a
8
+ * modern client uses to receive `notifications/resources/updated` for
9
+ * `resourceSubscriptions: [uri, ...]`) never consulted scopes at all — a
10
+ * client holding only `prompts:read` could still subscribe to
11
+ * `user://profile` (which requires `profile:read`) and would receive a
12
+ * `resource_updated` event the moment that resource actually changed,
13
+ * despite never having been granted `profile:read`. That is a real
14
+ * authorization bypass: it leaks the *fact* that a scoped resource changed
15
+ * to a caller who was never allowed to read its contents.
16
+ *
17
+ * Root cause of why this could not simply reuse `assertRequiredScope`
18
+ * in-place: the installed `@modelcontextprotocol/server@2.0.0` SDK serves
19
+ * `subscriptions/listen` entirely outside the registered-handler dispatch
20
+ * this factory wires up. Confirmed by reading the SDK's own bundled
21
+ * `createMcpHandler` (`dist/index.mjs`): on a `subscriptions/listen`
22
+ * request it builds a FRESH server via the factory, reads only
23
+ * `server.getCapabilities()` off it, immediately calls `product.close()`,
24
+ * and hands the request to its own internal `listenRouter.serve(...)` —
25
+ * the constructed `McpServer` instance (and therefore anything registered
26
+ * on it, including `assertRequiredScope`'s call sites) never sees the
27
+ * request at all, and the factory itself is never even passed the
28
+ * requested `resourceSubscriptions` URIs to filter against. There is
29
+ * consequently no request-handler hook inside `createMcpServer` capable of
30
+ * enforcing this — the enforcement point has to live at the HTTP boundary
31
+ * that owns the raw request body, before it is ever handed to
32
+ * `McpHttpHandler.fetch()`.
33
+ *
34
+ * **A consumer wiring its own handler MUST call this before dispatch.** It is
35
+ * not invoked from `createMcpServer`, and it cannot be: `subscriptions/listen`
36
+ * is decided at the HTTP boundary, before the request reaches this
37
+ * `McpServer` at all. So wrapping `createMcpServer()` directly in the SDK's
38
+ * `createMcpHandler` — the obvious minimal wiring, and the shape this
39
+ * package's own tests use — leaves every scoped resource observable by an
40
+ * under-scoped client, because nothing checks. `applications/web`'s
41
+ * `mcp-handler.ts` is the worked example of doing it correctly.
42
+ *
43
+ * That this is a documented obligation rather than an enforced one is a real
44
+ * gap, tracked upstream: a consumer that never reads this comment gets no
45
+ * error, just a silent authorization bypass on subscription delivery.
46
+ *
47
+ * This function is the reusable piece `createMcpServer` CAN own: the same
48
+ * scope-lookup `assertRequiredScope` performs (grantedScopes vs. a
49
+ * resource definition's `requiredScope`), applied per requested URI against
50
+ * the registry's resources, the single source of truth for which scope each resource
51
+ * needs. `applications/web/src/lib/mcp-handler.ts` already peeks the
52
+ * request body to detect a `subscriptions/listen` call before dispatch
53
+ * (see `isSubscriptionsListenRequest`, added for an unrelated shutdown-
54
+ * tracking reason) — that is the natural call site for this function: read
55
+ * `params.notifications.resourceSubscriptions` off the same already-parsed
56
+ * body, call this with the caller's verified `scopes`, and refuse the
57
+ * WHOLE request (a single JSON-RPC error, not a per-URI partial ack) when
58
+ * it returns `false`.
59
+ *
60
+ * Design decision — reject the whole request, not a filtered subset:
61
+ * silently attaching only the permitted URIs while acking the rest would
62
+ * (a) never inform the client which of its requested subscriptions it
63
+ * actually got, and (b) let a caller distinguish "URI exists but I lack
64
+ * scope" from "URI doesn't exist" by comparing which URIs it lists in an
65
+ * absence-of-updates versus an outright rejection — a probe channel. A
66
+ * single all-or-nothing rejection, mirroring how `resources/read` already
67
+ * collapses "expired token" and "wrong audience" into one wire response
68
+ * (see `mcp-routes.ts`'s `OBS-001` comment), discloses nothing about which
69
+ * specific URI(s) failed or why. Fails closed: an unrecognized URI is
70
+ * treated identically to a recognized-but-under-scoped one (both deny),
71
+ * so denial never confirms or denies a resource's existence either.
72
+ */
73
+ export declare function areResourceSubscriptionsAuthorized(uris: readonly string[], scopes: readonly string[], registry: McpRegistry): boolean;
74
+ export declare function createMcpServer(context: {
75
+ userId: string;
76
+ user: McpUserProfile;
77
+ /**
78
+ * OBS-001: the HTTP-boundary request identifier, threaded through to
79
+ * every tool/resource/prompt handler via `McpContext.requestId` so one
80
+ * connector action can be traced end to end through logs. Undefined for
81
+ * callers that build a server outside a real HTTP request (the
82
+ * standalone conformance server, tests).
83
+ */
84
+ requestId?: string;
85
+ enableUiExtension: boolean;
86
+ enableConformanceMode?: boolean;
87
+ /**
88
+ * PROTO-002: which protocol era this particular `McpServer` instance
89
+ * will serve. Drives whether `resources.subscribe` is advertised (only
90
+ * ever true on `'modern'` — see `buildServerCapabilities`) — legacy
91
+ * serving has no delivery path for a subscription push. Defaults to
92
+ * `'legacy'` so existing callers (tests, the standalone conformance
93
+ * server) that do not pass it keep today's unadvertised behavior.
94
+ */
95
+ era?: 'legacy' | 'modern';
96
+ /**
97
+ * PROTO-002 / S-11: publishes a `notifications/resources/updated` event
98
+ * scoped to only this context's `userId` (see
99
+ * `applications/web/src/lib/mcp-user-event-bus.ts`). Undefined when no
100
+ * event bus is wired for this request (e.g. the standalone conformance
101
+ * server) — `resources/subscribe` still acks, it just never delivers.
102
+ */
103
+ publishResourceUpdate?: (uri: string) => Promise<void>;
104
+ /**
105
+ * AUTHZ-001: the OAuth scopes the caller's access token actually carries
106
+ * (`McpRequestAuthExtra.scopes`, verified against the database by the
107
+ * HTTP boundary before this factory is ever called). Enforced here,
108
+ * once, before any tool/resource/prompt handler runs — "missing scopes
109
+ * fail before application data is read," per the roadmap's own wording
110
+ * for this item.
111
+ */
112
+ scopes: readonly string[];
113
+ }, registry: McpRegistry): McpServer;
@@ -0,0 +1,25 @@
1
+ import type { McpRegistry } from './scope-vocabulary.js';
2
+ /**
3
+ * AUTHZ-001: the scopes an OAuth client can actually request and see
4
+ * advertised, derived mechanically from the *production* registries
5
+ * (`tools`/`resources`/`prompts` — never `conformanceOnlyTools`, which is
6
+ * only ever registered when `enableConformanceMode` is on and is never
7
+ * reachable through a real deployment's OAuth flow). Computing this from the
8
+ * registry itself, rather than hand-maintaining a parallel list, is what
9
+ * makes "authorization server and protected-resource metadata publish the
10
+ * same supported scopes" mechanically true everywhere this is called from,
11
+ * and what keeps a conformance-only fixture's scope out of production
12
+ * metadata without a second place that has to remember to exclude it.
13
+ *
14
+ * The registry is an argument rather than a module import so that a
15
+ * consumer's advertised `scopes_supported` describes the server it is
16
+ * actually running. Reading module-level barrels here would have made this
17
+ * answer this package's question no matter whose primitives were being
18
+ * served, which is precisely the bug that made the package unusable as a
19
+ * library.
20
+ *
21
+ * Sorted for a stable, deterministic `scope` string wherever this is joined
22
+ * with a space (metadata `scopes_supported`, the `/mcp` 401 challenge's
23
+ * `scope` attribute).
24
+ */
25
+ export declare function getSupportedScopes(registry: McpRegistry): string[];
@@ -0,0 +1,16 @@
1
+ import type { McpRegistry } from './scope-vocabulary.js';
2
+ import type { McpScope } from './scopes.js';
3
+ /**
4
+ * This repository's own registry, assembled from the barrels above.
5
+ *
6
+ * It exists because `createMcpServer` and `getSupportedScopes` now take a
7
+ * registry rather than reaching for module-level constants, and this
8
+ * repository is itself one of their consumers. A second consumer builds its
9
+ * own `McpRegistry` and passes that instead — which is the whole point of
10
+ * the change, and the reason the registry is a required argument rather
11
+ * than one defaulting to this value. A default here would mean a consumer
12
+ * that forgot to pass its own silently served `get_user_profile` in
13
+ * production, and this package already holds the position that a wrong
14
+ * default is worse than a missing one.
15
+ */
16
+ export declare const templateRegistry: McpRegistry<McpScope>;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * SEC-004: the cap is measured in UTF-8 bytes, which is what actually goes on
3
+ * the wire — not `String.length`, which counts UTF-16 code units.
4
+ *
5
+ * The two diverge by up to 3x for non-ASCII output: 250,000 CJK characters
6
+ * satisfy a 256K *character* check and encode to roughly 750KB, nearly three
7
+ * times the advertised limit, on a bound whose entire purpose is stopping
8
+ * oversized payloads reaching a client.
9
+ *
10
+ * That defect survived its own tests because they pad with ASCII, where
11
+ * characters and bytes coincide — the cap read as enforced while the
12
+ * guarantee was absent for exactly the inputs that would breach it.
13
+ */
14
+ /**
15
+ * Counts UTF-8 bytes without materializing the encoded payload.
16
+ *
17
+ * `TextEncoder.encode()` would be the obvious way to measure this, and it is
18
+ * the wrong one here: it allocates a second buffer holding the entire encoded
19
+ * result, up to three times the string's UTF-16 length, *before* the cap can
20
+ * reject anything. That puts the largest allocation on exactly the oversized
21
+ * multi-byte responses this bound exists to refuse — a guard that can exhaust
22
+ * memory on the input it was added to stop.
23
+ *
24
+ * Iterating instead keeps the extra memory at one integer. `for...of` walks
25
+ * code points rather than code units, so a surrogate pair is seen once as a
26
+ * single value above `0xFFFF` and correctly counted as four bytes; a lone
27
+ * surrogate is yielded on its own and lands in the three-byte branch, which
28
+ * matches how `TextEncoder` encodes it (as U+FFFD, also three bytes).
29
+ *
30
+ * It counts the whole string rather than stopping at the cap, deliberately:
31
+ * the error reports the real byte length, and that number is the only thing
32
+ * telling whoever hit the limit how far over they were. Counting is bounded
33
+ * work on a string that already exists in memory; allocating a copy of it was
34
+ * the actual problem.
35
+ */
36
+ declare function utf8ByteLength(text: string): number;
37
+ /** Exported for the test that pins this against `TextEncoder`. */
38
+ export declare const __utf8ByteLengthForTests: typeof utf8ByteLength;
39
+ export declare function createToolTextResponse(text: string): {
40
+ content: [{
41
+ type: "text";
42
+ text: string;
43
+ }];
44
+ } | {
45
+ isError: boolean;
46
+ content: [{
47
+ type: "text";
48
+ text: string;
49
+ }];
50
+ };
51
+ export declare function createToolJsonResponse(data: unknown): {
52
+ content: [{
53
+ type: "text";
54
+ text: string;
55
+ }];
56
+ } | {
57
+ isError: boolean;
58
+ content: [{
59
+ type: "text";
60
+ text: string;
61
+ }];
62
+ };
63
+ export declare function createToolErrorResponse(message: string): {
64
+ isError: boolean;
65
+ content: [{
66
+ type: "text";
67
+ text: string;
68
+ }];
69
+ };
70
+ /**
71
+ * META-001: the response shape for a tool that declares an `outputSchema`.
72
+ * `structuredContent` carries the data a client validates against that
73
+ * schema; `summary` is the separate, intentional human-readable text the
74
+ * roadmap asks for ("text content only for an intentional human-readable
75
+ * summary") rather than a second copy of the same JSON as text.
76
+ *
77
+ * Both the summary and the structured payload go through the same
78
+ * SEC-004 size bound as every other tool response.
79
+ */
80
+ export declare function createToolStructuredResponse<T>(data: T, summary: string): {
81
+ content: {
82
+ type: "text";
83
+ text: string;
84
+ }[];
85
+ isError: boolean;
86
+ } | {
87
+ structuredContent: T;
88
+ content: [{
89
+ type: "text";
90
+ text: string;
91
+ }];
92
+ isError?: undefined;
93
+ };
94
+ export {};
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+ export declare const getUserProfileTool: import("../index.js").McpToolDefinition<z.ZodObject<{}, z.core.$strip>, z.ZodObject<{
3
+ id: z.ZodString;
4
+ email: z.ZodString;
5
+ name: z.ZodString;
6
+ image: z.ZodNullable<z.ZodString>;
7
+ role: z.ZodString;
8
+ }, z.core.$strip>, "profile:read" | "audit:read" | "prompts:read">;
@@ -0,0 +1,16 @@
1
+ import type { z } from 'zod';
2
+ import type { McpToolDefinition } from '../types/primitives.js';
3
+ import type { McpScope } from '../scopes.js';
4
+ export { getUserProfileTool } from './get-user-profile.js';
5
+ export { listAuditEventsTool } from './list-audit-events.js';
6
+ /**
7
+ * The widest legal element type for a heterogeneous registry, pinned to this
8
+ * repository's own vocabulary. The schema parameters stay at their defaults
9
+ * for the reason the `McpToolDefinition` comment gives — the handler is a
10
+ * method shorthand, so parameter checking is bivariant and a concretely
11
+ * typed tool can live in this array without widening its own handler by
12
+ * hand.
13
+ */
14
+ type TemplateTool = McpToolDefinition<z.ZodType, z.ZodType | undefined, McpScope>;
15
+ export declare const allTools: TemplateTool[];
16
+ export declare const conformanceOnlyTools: TemplateTool[];