@blen/uspto-mcp-server 0.0.0-stage → 0.1.2

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 (201) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +55 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +142 -0
  6. package/dist/accounts/app.d.ts +18 -0
  7. package/dist/accounts/app.d.ts.map +1 -0
  8. package/dist/accounts/app.js +407 -0
  9. package/dist/accounts/app.js.map +1 -0
  10. package/dist/accounts/config.d.ts +21 -0
  11. package/dist/accounts/config.d.ts.map +1 -0
  12. package/dist/accounts/config.js +55 -0
  13. package/dist/accounts/config.js.map +1 -0
  14. package/dist/accounts/crypto.d.ts +18 -0
  15. package/dist/accounts/crypto.d.ts.map +1 -0
  16. package/dist/accounts/crypto.js +43 -0
  17. package/dist/accounts/crypto.js.map +1 -0
  18. package/dist/accounts/keyGates.d.ts +19 -0
  19. package/dist/accounts/keyGates.d.ts.map +1 -0
  20. package/dist/accounts/keyGates.js +47 -0
  21. package/dist/accounts/keyGates.js.map +1 -0
  22. package/dist/accounts/paths.d.ts +10 -0
  23. package/dist/accounts/paths.d.ts.map +1 -0
  24. package/dist/accounts/paths.js +10 -0
  25. package/dist/accounts/paths.js.map +1 -0
  26. package/dist/accounts/portal.d.ts +7 -0
  27. package/dist/accounts/portal.d.ts.map +1 -0
  28. package/dist/accounts/portal.js +225 -0
  29. package/dist/accounts/portal.js.map +1 -0
  30. package/dist/accounts/provider.d.ts +2610 -0
  31. package/dist/accounts/provider.d.ts.map +1 -0
  32. package/dist/accounts/provider.js +108 -0
  33. package/dist/accounts/provider.js.map +1 -0
  34. package/dist/accounts/runtime.d.ts +26 -0
  35. package/dist/accounts/runtime.d.ts.map +1 -0
  36. package/dist/accounts/runtime.js +168 -0
  37. package/dist/accounts/runtime.js.map +1 -0
  38. package/dist/accounts/store.d.ts +30 -0
  39. package/dist/accounts/store.d.ts.map +1 -0
  40. package/dist/accounts/store.js +155 -0
  41. package/dist/accounts/store.js.map +1 -0
  42. package/dist/bin.d.ts +3 -0
  43. package/dist/bin.d.ts.map +1 -0
  44. package/dist/bin.js +195 -0
  45. package/dist/bin.js.map +1 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +8 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/sandbox/deno.d.ts +35 -0
  51. package/dist/sandbox/deno.d.ts.map +1 -0
  52. package/dist/sandbox/deno.js +373 -0
  53. package/dist/sandbox/deno.js.map +1 -0
  54. package/dist/sandbox/index.d.ts +28 -0
  55. package/dist/sandbox/index.d.ts.map +1 -0
  56. package/dist/sandbox/index.js +55 -0
  57. package/dist/sandbox/index.js.map +1 -0
  58. package/dist/sandbox/isolate.d.ts +17 -0
  59. package/dist/sandbox/isolate.d.ts.map +1 -0
  60. package/dist/sandbox/isolate.js +195 -0
  61. package/dist/sandbox/isolate.js.map +1 -0
  62. package/dist/sandbox/limits.d.ts +60 -0
  63. package/dist/sandbox/limits.d.ts.map +1 -0
  64. package/dist/sandbox/limits.js +86 -0
  65. package/dist/sandbox/limits.js.map +1 -0
  66. package/dist/sandbox/policy.d.ts +7 -0
  67. package/dist/sandbox/policy.d.ts.map +1 -0
  68. package/dist/sandbox/policy.js +87 -0
  69. package/dist/sandbox/policy.js.map +1 -0
  70. package/dist/sandbox/types.d.ts +57 -0
  71. package/dist/sandbox/types.d.ts.map +1 -0
  72. package/dist/sandbox/types.js +6 -0
  73. package/dist/sandbox/types.js.map +1 -0
  74. package/dist/sdk/bindings.d.ts +13 -0
  75. package/dist/sdk/bindings.d.ts.map +1 -0
  76. package/dist/sdk/bindings.js +22 -0
  77. package/dist/sdk/bindings.js.map +1 -0
  78. package/dist/sdk/odp-client.d.ts +167 -0
  79. package/dist/sdk/odp-client.d.ts.map +1 -0
  80. package/dist/sdk/odp-client.js +253 -0
  81. package/dist/sdk/odp-client.js.map +1 -0
  82. package/dist/sdk/runtime.d.ts +21 -0
  83. package/dist/sdk/runtime.d.ts.map +1 -0
  84. package/dist/sdk/runtime.js +32 -0
  85. package/dist/sdk/runtime.js.map +1 -0
  86. package/dist/sdk/sources/corpus-loader.d.ts +8 -0
  87. package/dist/sdk/sources/corpus-loader.d.ts.map +1 -0
  88. package/dist/sdk/sources/corpus-loader.js +17 -0
  89. package/dist/sdk/sources/corpus-loader.js.map +1 -0
  90. package/dist/sdk/sources/index.d.ts +8 -0
  91. package/dist/sdk/sources/index.d.ts.map +1 -0
  92. package/dist/sdk/sources/index.js +25 -0
  93. package/dist/sdk/sources/index.js.map +1 -0
  94. package/dist/sdk/sources/odp.d.ts +5 -0
  95. package/dist/sdk/sources/odp.d.ts.map +1 -0
  96. package/dist/sdk/sources/odp.js +78 -0
  97. package/dist/sdk/sources/odp.js.map +1 -0
  98. package/dist/sdk/sources/source.d.ts +44 -0
  99. package/dist/sdk/sources/source.d.ts.map +1 -0
  100. package/dist/sdk/sources/source.js +3 -0
  101. package/dist/sdk/sources/source.js.map +1 -0
  102. package/dist/sdk/sources/tsdr.d.ts +5 -0
  103. package/dist/sdk/sources/tsdr.d.ts.map +1 -0
  104. package/dist/sdk/sources/tsdr.js +38 -0
  105. package/dist/sdk/sources/tsdr.js.map +1 -0
  106. package/dist/sdk/tsdr-client.d.ts +24 -0
  107. package/dist/sdk/tsdr-client.d.ts.map +1 -0
  108. package/dist/sdk/tsdr-client.js +65 -0
  109. package/dist/sdk/tsdr-client.js.map +1 -0
  110. package/dist/search/bm25.d.ts +25 -0
  111. package/dist/search/bm25.d.ts.map +1 -0
  112. package/dist/search/bm25.js +67 -0
  113. package/dist/search/bm25.js.map +1 -0
  114. package/dist/search/corpus.d.ts +24 -0
  115. package/dist/search/corpus.d.ts.map +1 -0
  116. package/dist/search/corpus.js +23 -0
  117. package/dist/search/corpus.js.map +1 -0
  118. package/dist/server/authz.d.ts +40 -0
  119. package/dist/server/authz.d.ts.map +1 -0
  120. package/dist/server/authz.js +70 -0
  121. package/dist/server/authz.js.map +1 -0
  122. package/dist/server/http.d.ts +44 -0
  123. package/dist/server/http.d.ts.map +1 -0
  124. package/dist/server/http.js +199 -0
  125. package/dist/server/http.js.map +1 -0
  126. package/dist/server/ipRateLimiter.d.ts +22 -0
  127. package/dist/server/ipRateLimiter.d.ts.map +1 -0
  128. package/dist/server/ipRateLimiter.js +58 -0
  129. package/dist/server/ipRateLimiter.js.map +1 -0
  130. package/dist/server/mcpServer.d.ts +22 -0
  131. package/dist/server/mcpServer.d.ts.map +1 -0
  132. package/dist/server/mcpServer.js +90 -0
  133. package/dist/server/mcpServer.js.map +1 -0
  134. package/dist/server/stdio.d.ts +3 -0
  135. package/dist/server/stdio.d.ts.map +1 -0
  136. package/dist/server/stdio.js +16 -0
  137. package/dist/server/stdio.js.map +1 -0
  138. package/dist/server/toolCatalog.d.ts +162 -0
  139. package/dist/server/toolCatalog.d.ts.map +1 -0
  140. package/dist/server/toolCatalog.js +83 -0
  141. package/dist/server/toolCatalog.js.map +1 -0
  142. package/dist/server/wellKnown.d.ts +16 -0
  143. package/dist/server/wellKnown.d.ts.map +1 -0
  144. package/dist/server/wellKnown.js +17 -0
  145. package/dist/server/wellKnown.js.map +1 -0
  146. package/dist/server/zodToJsonSchema.d.ts +8 -0
  147. package/dist/server/zodToJsonSchema.d.ts.map +1 -0
  148. package/dist/server/zodToJsonSchema.js +14 -0
  149. package/dist/server/zodToJsonSchema.js.map +1 -0
  150. package/dist/supervisor/index.d.ts +54 -0
  151. package/dist/supervisor/index.d.ts.map +1 -0
  152. package/dist/supervisor/index.js +62 -0
  153. package/dist/supervisor/index.js.map +1 -0
  154. package/dist/tools/describeSchema.d.ts +23 -0
  155. package/dist/tools/describeSchema.d.ts.map +1 -0
  156. package/dist/tools/describeSchema.js +14 -0
  157. package/dist/tools/describeSchema.js.map +1 -0
  158. package/dist/tools/execute.d.ts +36 -0
  159. package/dist/tools/execute.d.ts.map +1 -0
  160. package/dist/tools/execute.js +70 -0
  161. package/dist/tools/execute.js.map +1 -0
  162. package/dist/tools/searchApi.d.ts +21 -0
  163. package/dist/tools/searchApi.d.ts.map +1 -0
  164. package/dist/tools/searchApi.js +14 -0
  165. package/dist/tools/searchApi.js.map +1 -0
  166. package/dist/util/executionContext.d.ts +6 -0
  167. package/dist/util/executionContext.d.ts.map +1 -0
  168. package/dist/util/executionContext.js +26 -0
  169. package/dist/util/executionContext.js.map +1 -0
  170. package/dist/util/executionLimiter.d.ts +19 -0
  171. package/dist/util/executionLimiter.d.ts.map +1 -0
  172. package/dist/util/executionLimiter.js +41 -0
  173. package/dist/util/executionLimiter.js.map +1 -0
  174. package/dist/util/httpClient.d.ts +116 -0
  175. package/dist/util/httpClient.d.ts.map +1 -0
  176. package/dist/util/httpClient.js +434 -0
  177. package/dist/util/httpClient.js.map +1 -0
  178. package/dist/util/logger.d.ts +7 -0
  179. package/dist/util/logger.d.ts.map +1 -0
  180. package/dist/util/logger.js +25 -0
  181. package/dist/util/logger.js.map +1 -0
  182. package/dist/util/quotas.d.ts +13 -0
  183. package/dist/util/quotas.d.ts.map +1 -0
  184. package/dist/util/quotas.js +29 -0
  185. package/dist/util/quotas.js.map +1 -0
  186. package/dist/util/tokenBucket.d.ts +11 -0
  187. package/dist/util/tokenBucket.d.ts.map +1 -0
  188. package/dist/util/tokenBucket.js +30 -0
  189. package/dist/util/tokenBucket.js.map +1 -0
  190. package/dist/util/upstreamGate.d.ts +36 -0
  191. package/dist/util/upstreamGate.d.ts.map +1 -0
  192. package/dist/util/upstreamGate.js +112 -0
  193. package/dist/util/upstreamGate.js.map +1 -0
  194. package/dist/web/THIRD_PARTY_NOTICES.txt +1940 -0
  195. package/dist/web/assets/blen-logo-BKJFojyj.png +0 -0
  196. package/dist/web/assets/index-Dbbu8lq3.js +317 -0
  197. package/dist/web/assets/index-DkKvyv-b.css +2 -0
  198. package/dist/web/index.html +14 -0
  199. package/package.json +127 -4
  200. package/schema/odp.json +743 -0
  201. package/schema/tsdr.json +129 -0
@@ -0,0 +1,70 @@
1
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
2
+ /** Bearer-token verification for the base HTTP transport. `none` is only valid with --insecure. */
3
+ export const AUTH_PROVIDERS = ['none', 'generic-oidc', 'clerk', 'workos', 'auth0'];
4
+ export class AuthConfigError extends Error {
5
+ constructor(message) { super(message); this.name = 'AuthConfigError'; }
6
+ }
7
+ export class InsufficientScopeError extends Error {
8
+ required;
9
+ constructor(required) {
10
+ super(`token lacks required scope(s): ${required.join(' ')}`);
11
+ this.required = required;
12
+ this.name = 'InsufficientScopeError';
13
+ }
14
+ }
15
+ /** Asymmetric algorithms only: a JWKS-verified token must never be accepted as HS256/none. */
16
+ const ALGORITHMS = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA'];
17
+ /** Scopes granted to a token, from `scope` (space-delimited) or `scp` (array). */
18
+ export function grantedScopes(claims) {
19
+ const raw = claims.scope ?? claims.scp;
20
+ if (typeof raw === 'string')
21
+ return raw.split(' ').filter(Boolean);
22
+ if (Array.isArray(raw))
23
+ return raw.filter((s) => typeof s === 'string');
24
+ return [];
25
+ }
26
+ export class OidcVerifier {
27
+ cfg;
28
+ keys;
29
+ constructor(cfg, keys) {
30
+ this.cfg = cfg;
31
+ if (!cfg.issuer)
32
+ throw new AuthConfigError('USPTO_AUTH_ISSUER is required for OIDC providers (the trusted token issuer).');
33
+ if (!cfg.audience)
34
+ throw new AuthConfigError('USPTO_AUTH_AUDIENCE is required for OIDC providers (tokens must be issued for this server).');
35
+ if (!keys) {
36
+ if (!cfg.jwksUrl)
37
+ throw new AuthConfigError('USPTO_AUTH_JWKS_URL is required for OIDC providers.');
38
+ const url = new URL(cfg.jwksUrl);
39
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
40
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
41
+ throw new AuthConfigError('USPTO_AUTH_JWKS_URL must use https (http only for a loopback development issuer).');
42
+ }
43
+ keys = createRemoteJWKSet(url);
44
+ }
45
+ this.keys = keys;
46
+ }
47
+ async verify(token) {
48
+ const { payload } = await jwtVerify(token, this.keys, {
49
+ issuer: this.cfg.issuer,
50
+ audience: this.cfg.audience,
51
+ algorithms: ALGORITHMS,
52
+ requiredClaims: ['exp', 'sub'],
53
+ });
54
+ if (typeof payload.sub !== 'string' || !payload.sub.trim())
55
+ throw new Error('token has no usable subject');
56
+ const scopes = grantedScopes(payload);
57
+ const missing = (this.cfg.scopes ?? []).filter(s => !scopes.includes(s));
58
+ if (missing.length)
59
+ throw new InsufficientScopeError(missing);
60
+ return { subject: payload.sub, claims: payload, scopes };
61
+ }
62
+ }
63
+ /** Throws AuthConfigError for an unknown provider or incomplete OIDC configuration. */
64
+ export function buildVerifier(cfg) {
65
+ if (!AUTH_PROVIDERS.includes(cfg.provider)) {
66
+ throw new AuthConfigError(`Unknown USPTO_AUTH_PROVIDER '${String(cfg.provider)}'. Use one of: ${AUTH_PROVIDERS.join(', ')} (or 'accounts' for Google sign-in accounts).`);
67
+ }
68
+ return cfg.provider === 'none' ? undefined : new OidcVerifier(cfg);
69
+ }
70
+ //# sourceMappingURL=authz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authz.js","sourceRoot":"","sources":["../../src/server/authz.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAyC,MAAM,MAAM,CAAC;AAE5F,mGAAmG;AACnG,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAC;AAwB5F,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,YAAY,OAAe,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC,CAAC,CAAC;CAChF;AAED,MAAM,OAAO,sBAAuB,SAAQ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OAAO,CAAC,CAAC;QAC9D,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IAC3D,CAAC;CACF;AAED,uFAAuF;AACvF,MAAM,UAAU,aAAa,CAAC,GAAe;IAC3C,IAAI,CAAE,cAAoC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,eAAe,CAAC,gCAAgC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,kBAAkB,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC;IAC5K,CAAC;IACD,OAAO,GAAG,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,GAAG,CAAC,CAAC;AACrE,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { CatalogDeps } from './toolCatalog.js';
2
+ import { type AuthConfig } from './authz.js';
3
+ export interface HttpOptions {
4
+ port: number;
5
+ host: string;
6
+ rps: number;
7
+ burst: number;
8
+ /**
9
+ * Header a reverse proxy in front of this server overwrites with the client address
10
+ * (Railway: `x-real-ip`). Unset keys the per-IP limit on the TCP peer, which behind a
11
+ * proxy is the proxy, not the client.
12
+ */
13
+ clientIpHeader?: string;
14
+ subjectDailyQuota: number;
15
+ auth: AuthConfig;
16
+ insecure?: boolean;
17
+ /**
18
+ * Extra Host header values accepted (DNS-rebinding protection). The public origin's host and
19
+ * loopback hosts on the listening port are always accepted. `['*']` disables the check
20
+ * (unsafe; only behind a proxy that validates Host itself).
21
+ */
22
+ allowedHosts?: string[];
23
+ /**
24
+ * Extra Origin header values allowed on the MCP endpoint (exact origin strings,
25
+ * e.g. "https://app.example.com"). The server's own origin and loopback origins
26
+ * are always allowed; requests without an Origin header (non-browser clients)
27
+ * always pass. Anything else is rejected with 403 — the MCP spec requires
28
+ * Origin validation to block DNS-rebinding / cross-site browser access.
29
+ */
30
+ allowedOrigins?: string[];
31
+ /** Public origin clients should use (for protected-resource metadata). */
32
+ publicOrigin?: string;
33
+ }
34
+ export interface HttpHandle {
35
+ close: () => Promise<void>;
36
+ port: number;
37
+ }
38
+ /** Largest MCP request body accepted (the tools take a code string of at most 256 KiB). */
39
+ export declare const MAX_REQUEST_BODY_BYTES: number;
40
+ export declare function originAllowed(originHeader: string, ownOrigin: string, allowlist: string[]): boolean;
41
+ /** The token of an `Authorization: Bearer <token>` header; the scheme is case-insensitive (RFC 9110). */
42
+ export declare function bearerToken(header: string | undefined): string | undefined;
43
+ export declare function startHttp(deps: CatalogDeps, opts: HttpOptions): Promise<HttpHandle>;
44
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/server/http.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGpD,OAAO,EAA0D,KAAK,UAAU,EAAE,MAAM,YAAY,CAAC;AAIrG,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,0EAA0E;IAC1E,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd;AAQD,2FAA2F;AAC3F,eAAO,MAAM,sBAAsB,QAAc,CAAC;AAclD,wBAAgB,aAAa,CAAC,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,OAAO,CASnG;AAED,yGAAyG;AACzG,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAE1E;AASD,wBAAsB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CA+JzF"}
@@ -0,0 +1,199 @@
1
+ import { createServer } from 'node:http';
2
+ import { createMcpHandler } from '@modelcontextprotocol/server';
3
+ import { toNodeHandler } from '@modelcontextprotocol/node';
4
+ import { buildMcpServer, MCP_PROTOCOL_VERSION } from './mcpServer.js';
5
+ import { IpRateLimiter, clientIp } from './ipRateLimiter.js';
6
+ import { SubjectQuota } from '../util/quotas.js';
7
+ import { buildVerifier, AuthConfigError, InsufficientScopeError } from './authz.js';
8
+ import { oauthProtectedResource } from './wellKnown.js';
9
+ import { log } from '../util/logger.js';
10
+ const MCP_PATH = '/mcp';
11
+ const RESOURCE_METADATA_PATH = '/.well-known/oauth-protected-resource/mcp';
12
+ /** Key the tool-catalog context off the subject this request authenticated as. */
13
+ const SUBJECT_KEY = 'uspto.subject';
14
+ /** Largest MCP request body accepted (the tools take a code string of at most 256 KiB). */
15
+ export const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
16
+ /** Cap on echoed error text: handler rejections quote caller-supplied headers and body. */
17
+ const MAX_LOGGED_ERROR_CHARS = 300;
18
+ function truncate(message) {
19
+ return message.length > MAX_LOGGED_ERROR_CHARS
20
+ ? `${message.slice(0, MAX_LOGGED_ERROR_CHARS)}…[truncated]`
21
+ : message;
22
+ }
23
+ /** Hostnames whose origins are always acceptable: local web tooling and dev UIs. */
24
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
25
+ export function originAllowed(originHeader, ownOrigin, allowlist) {
26
+ const value = originHeader.toLowerCase();
27
+ if (value === ownOrigin.toLowerCase())
28
+ return true;
29
+ if (allowlist.some(allowed => allowed.toLowerCase() === value))
30
+ return true;
31
+ try {
32
+ return LOOPBACK_HOSTNAMES.has(new URL(value).hostname);
33
+ }
34
+ catch {
35
+ return false; // unparseable Origin (including "null") is not allowed
36
+ }
37
+ }
38
+ /** The token of an `Authorization: Bearer <token>` header; the scheme is case-insensitive (RFC 9110). */
39
+ export function bearerToken(header) {
40
+ return /^bearer +(\S+)$/i.exec(header ?? '')?.[1];
41
+ }
42
+ function subjectOf(ctx) {
43
+ const s = ctx.authInfo?.extra?.[SUBJECT_KEY];
44
+ return typeof s === 'string' ? s : undefined;
45
+ }
46
+ const isLoopbackHost = (host) => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase());
47
+ export async function startHttp(deps, opts) {
48
+ const verifier = buildVerifier(opts.auth);
49
+ if (!verifier && !opts.insecure) {
50
+ throw new AuthConfigError('--http needs authentication: set USPTO_AUTH_PROVIDER (generic-oidc, clerk, workos, auth0) with USPTO_AUTH_ISSUER, USPTO_AUTH_AUDIENCE and USPTO_AUTH_JWKS_URL, use USPTO_AUTH_PROVIDER=accounts, or pass --insecure for an unauthenticated local server.');
51
+ }
52
+ const disableHostCheck = opts.allowedHosts?.length === 1 && opts.allowedHosts[0] === '*';
53
+ const explicitHosts = (opts.allowedHosts ?? []).filter(h => h !== '*').map(h => h.toLowerCase());
54
+ const publicUrl = opts.publicOrigin ? new URL(opts.publicOrigin) : undefined;
55
+ if (!isLoopbackHost(opts.host) && !publicUrl && !explicitHosts.length && !disableHostCheck) {
56
+ throw new AuthConfigError(`Listening on ${opts.host} needs the hostnames clients use: set USPTO_PUBLIC_ORIGIN (e.g. https://mcp.example.com) or USPTO_ALLOWED_HOSTS. Requests are checked against them to block DNS rebinding.`);
57
+ }
58
+ const limiter = new IpRateLimiter(opts.rps, opts.burst);
59
+ const quota = new SubjectQuota(opts.subjectDailyQuota);
60
+ // Stateless: the factory runs once per request, so the subject a tool sees is always the
61
+ // one this request's own bearer token verified as. There is no session to bind, reuse, or
62
+ // outlive a token — per-tenant quota attribution follows from re-authenticating every call.
63
+ const mcpHandler = createMcpHandler((ctx) => buildMcpServer(deps, { subject: subjectOf(ctx) }), {
64
+ legacy: 'stateless',
65
+ maxRequestBodySize: MAX_REQUEST_BODY_BYTES,
66
+ // This server declares only `tools`, but the SDK routes `subscriptions/listen`
67
+ // regardless and would otherwise hold up to 1024 long-lived SSE streams per handler
68
+ // — unbounded long-lived state of exactly the kind `USPTO_MAX_SESSIONS` used to cap.
69
+ // `0` refuses every listen request (the limit check is `open.size >= max`).
70
+ maxSubscriptions: 0,
71
+ // Rejections carry attacker-supplied header/body fragments, so cap what reaches stderr.
72
+ onerror: (err) => log.warn('mcp.handler.error', { error: truncate(err.message) }),
73
+ });
74
+ const nodeHandler = toNodeHandler(mcpHandler, {
75
+ onerror: (err) => log.warn('mcp.adapter.error', { error: truncate(err.message) }),
76
+ });
77
+ const server = createServer(async (req, res) => {
78
+ try {
79
+ const ip = clientIp(req, opts.clientIpHeader);
80
+ if (!limiter.allow(ip))
81
+ return reply(res, 429, { error: 'rate_limited' });
82
+ // DNS rebinding protection: the Host header must be one we were configured with. The
83
+ // trusted origin is never derived from the request itself.
84
+ const host = String(req.headers.host ?? '').toLowerCase();
85
+ if (!disableHostCheck && !trustedHosts.has(host)) {
86
+ return reply(res, 421, { error: 'host_not_allowed' });
87
+ }
88
+ const origin = ownOrigin;
89
+ const url = new URL(req.url ?? '/', origin);
90
+ if (url.pathname === RESOURCE_METADATA_PATH && req.method === 'GET') {
91
+ return reply(res, 200, oauthProtectedResource(opts.auth, `${origin}${MCP_PATH}`));
92
+ }
93
+ if (url.pathname === '/health' && req.method === 'GET') {
94
+ return reply(res, 200, { ok: true, sandbox: deps.sandbox.kind, protocolVersion: MCP_PROTOCOL_VERSION });
95
+ }
96
+ if (url.pathname === MCP_PATH) {
97
+ // Origin validation (MCP spec MUST): a browser-originated cross-site request
98
+ // must not reach the transport. Non-browser clients send no Origin and pass.
99
+ const originHeader = req.headers.origin;
100
+ if (typeof originHeader === 'string' && !originAllowed(originHeader, origin, [...(opts.allowedOrigins ?? []), ...(publicUrl ? [publicUrl.origin] : [])])) {
101
+ return reply(res, 403, { error: 'origin_not_allowed', origin: originHeader });
102
+ }
103
+ // Auth (unless --insecure). Runs on every request: with no protocol session there
104
+ // is no other point at which a caller's identity could have been established.
105
+ let subject = 'anonymous';
106
+ let token = '';
107
+ let scopes = [];
108
+ if (verifier && !opts.insecure) {
109
+ const bearer = bearerToken(req.headers.authorization);
110
+ if (!bearer) {
111
+ res.writeHead(401, {
112
+ 'content-type': 'application/json',
113
+ 'www-authenticate': `Bearer resource_metadata="${origin}${RESOURCE_METADATA_PATH}"`,
114
+ });
115
+ return res.end(JSON.stringify({ error: 'unauthorized' }));
116
+ }
117
+ token = bearer;
118
+ try {
119
+ const ctx = await verifier.verify(token);
120
+ subject = ctx.subject;
121
+ scopes = ctx.scopes;
122
+ }
123
+ catch (err) {
124
+ if (err instanceof InsufficientScopeError) {
125
+ res.writeHead(403, {
126
+ 'content-type': 'application/json',
127
+ 'www-authenticate': `Bearer resource_metadata="${origin}${RESOURCE_METADATA_PATH}", error="insufficient_scope", scope="${err.required.join(' ')}"`,
128
+ });
129
+ return res.end(JSON.stringify({ error: 'insufficient_scope' }));
130
+ }
131
+ res.writeHead(401, {
132
+ 'content-type': 'application/json',
133
+ 'www-authenticate': `Bearer resource_metadata="${origin}${RESOURCE_METADATA_PATH}", error="invalid_token"`,
134
+ });
135
+ return res.end(JSON.stringify({ error: 'invalid_token' })); // verifier details stay server-side
136
+ }
137
+ const q = quota.consume(subject);
138
+ if (!q.allowed) {
139
+ return reply(res, 429, { error: 'quota_exceeded', resetAt: new Date(q.resetAt).toISOString() });
140
+ }
141
+ }
142
+ // toNodeHandler forwards `req.auth` to the factory as pass-through authInfo.
143
+ const authInfo = {
144
+ token,
145
+ clientId: subject,
146
+ scopes,
147
+ extra: { [SUBJECT_KEY]: subject },
148
+ };
149
+ req.auth = authInfo;
150
+ await nodeHandler(req, res);
151
+ return;
152
+ }
153
+ reply(res, 404, { error: 'not_found' });
154
+ }
155
+ catch (err) {
156
+ log.error('http.unhandled', { error: err.message, stack: err.stack });
157
+ if (!res.headersSent)
158
+ reply(res, 500, { error: 'internal' });
159
+ }
160
+ });
161
+ let ownOrigin = '';
162
+ let trustedHosts = new Set();
163
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(opts.port, opts.host, () => resolve()); });
164
+ const addr = server.address();
165
+ const actualPort = typeof addr === 'object' && addr ? addr.port : opts.port;
166
+ ownOrigin = publicUrl?.origin ?? `http://127.0.0.1:${actualPort}`;
167
+ trustedHosts = new Set([
168
+ ...explicitHosts,
169
+ ...(publicUrl ? [publicUrl.host.toLowerCase()] : []),
170
+ // Local clients and the container health check always reach us on loopback.
171
+ ...['localhost', '127.0.0.1', '[::1]'].map(h => `${h}:${actualPort}`),
172
+ ]);
173
+ if (opts.insecure && !isLoopbackHost(opts.host)) {
174
+ log.warn('http.insecure_public', { host: opts.host, note: 'unauthenticated server reachable beyond this machine' });
175
+ }
176
+ log.info('http.listening', {
177
+ host: opts.host, port: actualPort,
178
+ insecure: opts.insecure ?? false,
179
+ sandbox: deps.sandbox.kind,
180
+ auth: opts.auth.provider,
181
+ protocolVersion: MCP_PROTOCOL_VERSION,
182
+ });
183
+ return {
184
+ port: actualPort,
185
+ close: async () => {
186
+ // Handler first: `server.close()` only stops new connections and resolves once every
187
+ // existing one is idle, so an open SSE exchange (kept warm by keepalive frames) would
188
+ // block it forever. Closing the handler aborts in-flight exchanges and releases those
189
+ // sockets, after which the listener can actually drain.
190
+ await mcpHandler.close();
191
+ await new Promise(r => server.close(() => r()));
192
+ },
193
+ };
194
+ }
195
+ function reply(res, status, body) {
196
+ res.writeHead(status, { 'content-type': 'application/json' });
197
+ res.end(JSON.stringify(body));
198
+ }
199
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/server/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,gBAAgB,EAAyC,MAAM,8BAA8B,CAAC;AACvG,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,sBAAsB,EAAmB,MAAM,YAAY,CAAC;AACrG,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAuCxC,MAAM,QAAQ,GAAG,MAAM,CAAC;AACxB,MAAM,sBAAsB,GAAG,2CAA2C,CAAC;AAE3E,kFAAkF;AAClF,MAAM,WAAW,GAAG,eAAe,CAAC;AAEpC,2FAA2F;AAC3F,MAAM,CAAC,MAAM,sBAAsB,GAAG,IAAI,GAAG,IAAI,CAAC;AAElD,2FAA2F;AAC3F,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,SAAS,QAAQ,CAAC,OAAe;IAC/B,OAAO,OAAO,CAAC,MAAM,GAAG,sBAAsB;QAC5C,CAAC,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,sBAAsB,CAAC,cAAc;QAC3D,CAAC,CAAC,OAAO,CAAC;AACd,CAAC;AAED,oFAAoF;AACpF,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,E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AAI,EAAE,UAAU;QACjC,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,KAAK;QAChC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI;QAC1B,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ;QACxB,eAAe,EAAE,oBAAoB;KACtC,CAAC,CAAC;IAEH,OAAO;QACL,IAAI,EAAE,UAAU;QAChB,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,qFAAqF;YACrF,sFAAsF;YACtF,sFAAsF;YACtF,wDAAwD;YACxD,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC;YACzB,MAAM,IAAI,OAAO,CAAO,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACxD,CAAC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,KAAK,CAAC,GAAmB,EAAE,MAAc,EAAE,IAAa;IAC/D,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAChC,CAAC"}
@@ -0,0 +1,22 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /**
3
+ * Token-bucket IP rate limiter. In-memory; one process.
4
+ */
5
+ export declare class IpRateLimiter {
6
+ private readonly rps;
7
+ private readonly burst;
8
+ private readonly buckets;
9
+ constructor(rps: number, burst: number);
10
+ allow(ip: string): boolean;
11
+ }
12
+ /**
13
+ * The caller's address. Without `trustedHeader` it is the TCP peer. Behind a reverse proxy
14
+ * the peer is the proxy (on Railway, a different internal 100.64.x.x address per
15
+ * connection), so name the header the proxy sets to the client address and that header is
16
+ * used instead. Only name a header the proxy always overwrites: a client could otherwise
17
+ * forge it. Railway overwrites `x-real-ip` (verified 2026-10-13; it also rebuilds
18
+ * X-Forwarded-For as "<client>, <edge>", so that header's rightmost entry is NOT the client).
19
+ * For a list-valued header the rightmost entry, the one the nearest proxy added, is used.
20
+ */
21
+ export declare function clientIp(req: IncomingMessage, trustedHeader?: string): string;
22
+ //# sourceMappingURL=ipRateLimiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipRateLimiter.d.ts","sourceRoot":"","sources":["../../src/server/ipRateLimiter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAGjD;;GAEG;AACH,qBAAa,aAAa;IAEZ,OAAO,CAAC,QAAQ,CAAC,GAAG;IAAU,OAAO,CAAC,QAAQ,CAAC,KAAK;IADhE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0D;IAClF,YAA6B,GAAG,EAAE,MAAM,EAAmB,KAAK,EAAE,MAAM,EASvE;IAED,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAazB;CACF;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,GAAG,EAAE,eAAe,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAQ7E"}
@@ -0,0 +1,58 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ /**
3
+ * Token-bucket IP rate limiter. In-memory; one process.
4
+ */
5
+ export class IpRateLimiter {
6
+ rps;
7
+ burst;
8
+ buckets;
9
+ constructor(rps, burst) {
10
+ this.rps = rps;
11
+ this.burst = burst;
12
+ // An idle bucket refills to `burst` within burst/rps seconds; after that it is
13
+ // indistinguishable from a new one, so it can be dropped. Bounded so a flood of
14
+ // distinct addresses cannot grow memory without limit.
15
+ // Clamped to a finite integer: lru-cache throws on a non-integer or infinite ttl, which
16
+ // rps = 0 or an extreme burst/rps ratio would otherwise produce.
17
+ const refillMs = Math.ceil((burst / rps) * 1000);
18
+ const ttl = Number.isFinite(refillMs) ? Math.min(Math.max(refillMs, 1000), Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;
19
+ this.buckets = new LRUCache({ max: 50_000, ttl });
20
+ }
21
+ allow(ip) {
22
+ const now = Date.now();
23
+ const b = this.buckets.get(ip) ?? { tokens: this.burst, updatedAt: now };
24
+ const elapsedSec = (now - b.updatedAt) / 1000;
25
+ b.tokens = Math.min(this.burst, b.tokens + elapsedSec * this.rps);
26
+ b.updatedAt = now;
27
+ if (b.tokens < 1) {
28
+ this.buckets.set(ip, b);
29
+ return false;
30
+ }
31
+ b.tokens -= 1;
32
+ this.buckets.set(ip, b);
33
+ return true;
34
+ }
35
+ }
36
+ /**
37
+ * The caller's address. Without `trustedHeader` it is the TCP peer. Behind a reverse proxy
38
+ * the peer is the proxy (on Railway, a different internal 100.64.x.x address per
39
+ * connection), so name the header the proxy sets to the client address and that header is
40
+ * used instead. Only name a header the proxy always overwrites: a client could otherwise
41
+ * forge it. Railway overwrites `x-real-ip` (verified 2026-10-13; it also rebuilds
42
+ * X-Forwarded-For as "<client>, <edge>", so that header's rightmost entry is NOT the client).
43
+ * For a list-valued header the rightmost entry, the one the nearest proxy added, is used.
44
+ */
45
+ export function clientIp(req, trustedHeader) {
46
+ const peer = normalize(req.socket.remoteAddress ?? 'unknown');
47
+ if (!trustedHeader)
48
+ return peer;
49
+ const value = req.headers[trustedHeader.toLowerCase()];
50
+ const entries = (Array.isArray(value) ? value.join(',') : value ?? '')
51
+ .split(',').map(s => s.trim()).filter(Boolean);
52
+ const candidate = entries[entries.length - 1];
53
+ return candidate ? normalize(candidate) : peer;
54
+ }
55
+ function normalize(ip) {
56
+ return ip.replace(/^::ffff:/, '');
57
+ }
58
+ //# sourceMappingURL=ipRateLimiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipRateLimiter.js","sourceRoot":"","sources":["../../src/server/ipRateLimiter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC;;GAEG;AACH,MAAM,OAAO,aAAa;IAEK,GAAG;IAA2B,KAAK;IAD/C,OA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O,KAAK,CAAC;QACf,CAAC;QACD,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;QACd,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAoB,EAAE,aAAsB;IACnE,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC,CAAC;IAC9D,IAAI,CAAC,aAAa;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;SACnE,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9C,OAAO,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACjD,CAAC;AAED,SAAS,SAAS,CAAC,EAAU;IAC3B,OAAO,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AACpC,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { type CatalogDeps } from './toolCatalog.js';
3
+ import type { RequestCtx } from '../tools/execute.js';
4
+ /**
5
+ * The MCP revision this server speaks.
6
+ *
7
+ * Declared here rather than imported: the SDK's exported `LATEST_PROTOCOL_VERSION` and
8
+ * `SUPPORTED_PROTOCOL_VERSIONS` describe only the legacy `initialize` era (`2025-11-25`
9
+ * and older) kept for the backward-compatibility leg. The SDK does hold the modern value
10
+ * as `FIRST_MODERN_PROTOCOL_VERSION`, but that lives in its `core-internal` package — not
11
+ * exported at runtime and absent from every published `.d.mts` — so it is not importable.
12
+ */
13
+ export declare const MCP_PROTOCOL_VERSION = "2026-07-28";
14
+ /**
15
+ * The tools take a few scalar arguments; anything with more array elements or object members
16
+ * than this is not a legitimate call (SDK guard against validation-cost DoS, GHSA-46jr-4wx8-v453).
17
+ */
18
+ export declare const MAX_TOOL_INPUT_ELEMENTS = 64;
19
+ /** Server-level guidance clients may show the model before it picks a tool. */
20
+ export declare const SERVER_INSTRUCTIONS: string;
21
+ export declare function buildMcpServer(deps: CatalogDeps, requestCtx?: RequestCtx): McpServer;
22
+ //# sourceMappingURL=mcpServer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcpServer.d.ts","sourceRoot":"","sources":["../../src/server/mcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAuC,MAAM,8BAA8B,CAAC;AAC9F,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAGtD;;;;;;;;GAQG;AACH,eAAO,MAAM,oBAAoB,eAAe,CAAC;AA2BjD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C,+EAA+E;AAC/E,eAAO,MAAM,mBAAmB,QAKpB,CAAC;AAEb,wBAAgB,cAAc,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE,UAAU,GAAG,SAAS,CAgDpF"}
@@ -0,0 +1,90 @@
1
+ import { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';
2
+ import { buildCatalog } from './toolCatalog.js';
3
+ import { log } from '../util/logger.js';
4
+ /**
5
+ * The MCP revision this server speaks.
6
+ *
7
+ * Declared here rather than imported: the SDK's exported `LATEST_PROTOCOL_VERSION` and
8
+ * `SUPPORTED_PROTOCOL_VERSIONS` describe only the legacy `initialize` era (`2025-11-25`
9
+ * and older) kept for the backward-compatibility leg. The SDK does hold the modern value
10
+ * as `FIRST_MODERN_PROTOCOL_VERSION`, but that lives in its `core-internal` package — not
11
+ * exported at runtime and absent from every published `.d.mts` — so it is not importable.
12
+ */
13
+ export const MCP_PROTOCOL_VERSION = '2026-07-28';
14
+ // The catalog is derived from process configuration (which sources are bound), not from
15
+ // the caller, so every tenant sees byte-identical results and a shared cache is safe.
16
+ const LIST_CACHE_HINT = { ttlMs: 300_000, cacheScope: 'public' };
17
+ /**
18
+ * Converted tool input schemas, cached for the process lifetime.
19
+ *
20
+ * `fromJsonSchema` compiles an Ajv validator, and the SDK's default validator is a module
21
+ * singleton that caches every compiled schema in a plain `Map` keyed by schema *identity*,
22
+ * with no eviction. Since `buildMcpServer` runs per request and `buildCatalog` mints fresh
23
+ * schema literals each time, converting inline would retain ~4 KB per call forever —
24
+ * roughly 12 KB per HTTP request, unbounded. The three tool inputs derive only from
25
+ * module-level Zod constants, so each is converted exactly once here.
26
+ */
27
+ const schemaCache = new Map();
28
+ function cachedSchema(key, jsonSchema) {
29
+ let converted = schemaCache.get(key);
30
+ if (!converted) {
31
+ converted = fromJsonSchema(jsonSchema);
32
+ schemaCache.set(key, converted);
33
+ }
34
+ return converted;
35
+ }
36
+ /**
37
+ * The tools take a few scalar arguments; anything with more array elements or object members
38
+ * than this is not a legitimate call (SDK guard against validation-cost DoS, GHSA-46jr-4wx8-v453).
39
+ */
40
+ export const MAX_TOOL_INPUT_ELEMENTS = 64;
41
+ /** Server-level guidance clients may show the model before it picks a tool. */
42
+ export const SERVER_INSTRUCTIONS = [
43
+ 'USPTO data through code mode. Workflow: search_api (find the SDK method and field names) -> describe_schema (exact signature) -> execute (run plain JavaScript against the odp and tsdr globals).',
44
+ 'odp = USPTO Open Data Portal: odp.patents.* (patent applications/file wrapper), odp.ptab.* (IPR/PGR trials, appeals, interferences), odp.petitions.*, odp.officeActions.*, odp.oa.* (legacy office action datasets), odp.bulk.* (bulk dataset catalog). tsdr = trademark status by serial or registration number.',
45
+ 'USPTO allows one request at a time per API key and has weekly quotas: use one well-filtered search with `fields` and a sensible `limit` rather than many lookups, and return only the values you need.',
46
+ 'Application numbers (e.g. 17/248,024) differ from patent numbers (e.g. 11,646,472): resolve a patent number with odp.patents.byPatentNumber first.',
47
+ ].join('\n');
48
+ export function buildMcpServer(deps, requestCtx) {
49
+ const server = new McpServer({ name: 'uspto-mcp-server', version: '0.1.2' }, // x-release-version
50
+ {
51
+ capabilities: { tools: {} },
52
+ instructions: SERVER_INSTRUCTIONS,
53
+ maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS,
54
+ cacheHints: { 'tools/list': LIST_CACHE_HINT, 'server/discover': LIST_CACHE_HINT },
55
+ });
56
+ for (const tool of buildCatalog(deps, requestCtx)) {
57
+ server.registerTool(tool.name, {
58
+ title: tool.title,
59
+ description: tool.description,
60
+ annotations: tool.annotations,
61
+ // The catalog emits JSON Schema; `fromJsonSchema` attaches the SDK's default Ajv
62
+ // validator, so arguments are checked here BEFORE the handler re-parses with Zod.
63
+ // Note `zodToJsonSchema` emits `additionalProperties: false`, so unknown argument
64
+ // keys are now rejected rather than silently stripped by Zod (see CHANGELOG).
65
+ inputSchema: cachedSchema(`in:${tool.name}`, tool.inputSchema),
66
+ outputSchema: cachedSchema(`out:${tool.name}`, tool.outputSchema),
67
+ }, async (args, ctx) => {
68
+ try {
69
+ const result = await tool.handler(args ?? {}, { signal: ctx?.mcpReq?.signal });
70
+ // Compact JSON for the model, the same object as structuredContent for clients, and
71
+ // isError for a failed execution (MCP tool-error convention) with the full envelope.
72
+ return {
73
+ content: [{ type: 'text', text: JSON.stringify(result) }],
74
+ structuredContent: result,
75
+ ...(tool.isFailure?.(result) ? { isError: true } : {}),
76
+ };
77
+ }
78
+ catch (err) {
79
+ const e = err;
80
+ log.warn('tool.error', { tool: tool.name, name: e.name, error: e.message });
81
+ return {
82
+ isError: true,
83
+ content: [{ type: 'text', text: `${e.name}: ${e.message}` }],
84
+ };
85
+ }
86
+ });
87
+ }
88
+ return server;
89
+ }
90
+ //# sourceMappingURL=mcpServer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcpServer.js","sourceRoot":"","sources":["../../src/server/mcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAuB,MAAM,8BAA8B,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAoB,MAAM,kBAAkB,CAAC;AAElE,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAEjD,wFAAwF;AACxF,sFAAsF;AACtF,MAAM,eAAe,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,QAAiB,EAAE,CAAC;AAE1E;;;;;;;;;GASG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,EAA6C,CAAC;AAEzE,SAAS,YAAY,CAAC,GAAW,EAAE,UAAmB;IACpD,IAAI,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACrC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,cAAc,CAAC,UAA4B,CAAC,CAAC;QACzD,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAE1C,+EAA+E;AAC/E,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,mMAAmM;IACnM,mTAAmT;IACnT,wMAAwM;IACxM,oJAAoJ;CACrJ,CAAC,IAAI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CAAC,EAAE,CAAC;oBAClE,iBAAiB,EAAE,MAAiC;oBACpD,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBACvD,CAAC;YACJ,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,GAAG,GAAY,CAAC;gBACvB,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;gBAC5E,OAAO;oBACL,OAAO,EAAE,IAAI;oBACb,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;iBACtE,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { CatalogDeps } from './toolCatalog.js';
2
+ export declare function startStdio(deps: CatalogDeps): Promise<void>;
3
+ //# sourceMappingURL=stdio.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/server/stdio.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGpD,wBAAsB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAWjE"}
@@ -0,0 +1,16 @@
1
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
+ import { buildMcpServer } from './mcpServer.js';
3
+ import { log } from '../util/logger.js';
4
+ export async function startStdio(deps) {
5
+ // stdio is unauthenticated and single-tenant, so there is no subject to scope quotas by.
6
+ //
7
+ // `serveStdio` reports every out-of-band failure (transport start, a throwing factory,
8
+ // message-pump errors) through `onerror` and swallows it otherwise. Without this the
9
+ // process would log `stdio.ready` and then answer every request with -32603 in silence;
10
+ // the v1 `await server.connect(transport)` at least rejected into `bin.fatal`.
11
+ serveStdio(() => buildMcpServer(deps), {
12
+ onerror: (err) => log.error('stdio.error', { name: err.name, error: err.message }),
13
+ });
14
+ log.info('stdio.ready', { sandbox: deps.sandbox.kind });
15
+ }
16
+ //# sourceMappingURL=stdio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../src/server/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,IAAiB;IAChD,yFAAyF;IACzF,EAAE;IACF,uFAAuF;IACvF,qFAAqF;IACrF,wFAAwF;IACxF,+EAA+E;IAC/E,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE;QACrC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,EAAE,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;KACnF,CAAC,CAAC;IACH,GAAG,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;AAC1D,CAAC"}