@lostgradient/mcp 0.1.0 → 0.2.1
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.
- package/README.md +68 -8
- package/dist/chunk-3ek3knfm.js +73 -0
- package/dist/{chunk-v14p4gng.js → chunk-3rr24vhh.js} +4 -1
- package/dist/chunk-6ekjtvcq.js +273 -0
- package/dist/chunk-7dpts3r9.js +909 -0
- package/dist/chunk-88nhf6xt.js +449 -0
- package/dist/{chunk-psnez3q2.js → chunk-k6fm3cmk.js} +23 -2
- package/dist/chunk-rxnyn7tf.js +19 -0
- package/dist/{chunk-mf3t0afg.js → chunk-wfty87ws.js} +1 -1
- package/dist/{chunk-wmkqd45r.js → chunk-xcf742mf.js} +1 -1
- package/dist/chunk-yf4nw40e.js +1102 -0
- package/dist/conformance.d.ts +43 -0
- package/dist/env.d.ts +1 -1
- package/dist/env.js +2 -2
- package/dist/environment-schema.d.ts +1 -1
- package/dist/environment-schema.js +1 -1
- package/dist/http/authenticate.d.ts +35 -0
- package/dist/http/authorization-header.d.ts +5 -0
- package/dist/http/grant-revocation-channel.d.ts +24 -0
- package/dist/http/handler.d.ts +32 -0
- package/dist/http/index.d.ts +27 -0
- package/dist/http/index.js +813 -0
- package/dist/http/request-context.d.ts +17 -0
- package/dist/http/responses.d.ts +11 -0
- package/dist/http/serving-layer.d.ts +18 -0
- package/dist/http/user-handler-cache.d.ts +37 -0
- package/dist/http/user-server-event-bus.d.ts +35 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +230 -940
- package/dist/logger.d.ts +20 -0
- package/dist/logger.js +9 -5
- package/dist/oauth/authorize-endpoint.d.ts +5 -0
- package/dist/oauth/canonicalize-ip-address.d.ts +20 -0
- package/dist/oauth/client-authentication.d.ts +10 -0
- package/dist/oauth/client-metadata-documents.d.ts +52 -0
- package/dist/oauth/client-metadata-documents.js +19 -0
- package/dist/oauth/discovery-metadata.d.ts +19 -0
- package/dist/oauth/endpoint-rate-limits.d.ts +10 -0
- package/dist/oauth/endpoint-responses.d.ts +10 -0
- package/dist/oauth/index.d.ts +214 -0
- package/dist/oauth/index.js +69 -0
- package/dist/oauth/network-identity.d.ts +32 -0
- package/dist/oauth/pkce-validation.d.ts +2 -0
- package/dist/oauth/postgres/client-store.d.ts +12 -0
- package/dist/oauth/postgres/code-store.d.ts +14 -0
- package/dist/oauth/postgres/database.d.ts +18 -0
- package/dist/oauth/postgres/index.d.ts +11 -0
- package/dist/oauth/postgres/index.js +584 -0
- package/dist/oauth/postgres/schema.d.ts +1455 -0
- package/dist/oauth/postgres/token-store.d.ts +16 -0
- package/dist/oauth/postgres/transaction-store.d.ts +14 -0
- package/dist/oauth/redirect-uri-matching.d.ts +2 -0
- package/dist/oauth/registration-endpoint.d.ts +2 -0
- package/dist/oauth/request-body.d.ts +14 -0
- package/dist/oauth/revocation-endpoint.d.ts +2 -0
- package/dist/oauth/safe-public-https-fetch.d.ts +28 -0
- package/dist/oauth/scope-utilities.d.ts +15 -0
- package/dist/oauth/security-utilities.d.ts +8 -0
- package/dist/oauth/stores.d.ts +225 -0
- package/dist/oauth/stores.js +0 -0
- package/dist/oauth/testing/contract-fixtures.d.ts +134 -0
- package/dist/oauth/testing/index.d.ts +56 -0
- package/dist/oauth/testing/index.js +330 -0
- package/dist/oauth/token-endpoint.d.ts +2 -0
- package/dist/oauth-scope-configuration.d.ts +3 -0
- package/dist/rate-limit/in-memory-sliding-window-store.d.ts +3 -0
- package/dist/rate-limit/index.d.ts +23 -0
- package/dist/rate-limit/index.js +29 -0
- package/dist/rate-limit/mcp-concurrency-limiter.d.ts +26 -0
- package/dist/rate-limit/rate-limit-response.d.ts +1 -0
- package/dist/rate-limit/redis-sliding-window-store.d.ts +2 -0
- package/dist/rate-limit/request-rate-limiter.d.ts +10 -0
- package/dist/rate-limit/sliding-window-rate-limiter.d.ts +16 -0
- package/dist/scopes.d.ts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/sveltekit-mount-state.d.ts +4 -0
- package/dist/sveltekit-mount.d.ts +43 -0
- package/dist/sveltekit-mount.js +332 -0
- package/dist/tool-response.d.ts +6 -0
- package/dist/types/primitives.d.ts +1 -1
- package/dist/ui-extension-support.d.ts +2 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +56 -4
package/README.md
CHANGED
|
@@ -91,6 +91,28 @@ If you would rather rely on the environment, set `NODE_ENV` (and any other varia
|
|
|
91
91
|
|
|
92
92
|
`getSupportedScopes(registry)` returns the sorted union of every scope your registry actually requires. Use it for the `scopes_supported` field of your OAuth metadata documents and for the `scope` attribute on a `401` challenge, rather than maintaining that list by hand.
|
|
93
93
|
|
|
94
|
+
## Running protocol conformance
|
|
95
|
+
|
|
96
|
+
`runMcpConformance` runs either protocol era against your registry. Discovery is checked automatically. Supply valid arguments only for the tools or prompts you want invoked, and resource URIs only for the resources you want read—the harness cannot safely invent valid consumer input.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { runMcpConformance } from '@lostgradient/mcp';
|
|
100
|
+
|
|
101
|
+
const results = await runMcpConformance({
|
|
102
|
+
era: 'modern', // or 'legacy'
|
|
103
|
+
registry,
|
|
104
|
+
scopeVocabulary: scopes,
|
|
105
|
+
identity: { userId: user.id, user },
|
|
106
|
+
toolProbes: { list_repositories: {} },
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
for (const result of results) {
|
|
110
|
+
console.log(result.name, result.status, result.error ?? '');
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Each result has a stable behavior name and its own `passed` or `failed` status. One failed tool, resource, or prompt probe does not hide the results of the remaining behaviors. Supply the same application identity every probe should use; otherwise the harness creates one stable synthetic identity for the run. The runner disables package-owned conformance fixtures so discovery reflects only the supplied registry. `createConsumerConformanceHandler` exposes the lower-level request handler when a consumer needs to drive its own client or explicitly enable those fixtures, including watched-resource notifications. Its localhost DNS-rebinding check runs independently of `enableConformanceMode`.
|
|
115
|
+
|
|
94
116
|
## Environment
|
|
95
117
|
|
|
96
118
|
Importing this package reads nothing from `process.env` and cannot throw, whatever the ambient environment. That is deliberate: a library which validates its host's environment during module evaluation cannot be embedded, because the host can neither catch the failure nor supply a different environment nor decide whether it wants a server at all.
|
|
@@ -109,16 +131,54 @@ const environment = parseMcpServerEnvironment(process.env);
|
|
|
109
131
|
|
|
110
132
|
`areResourceSubscriptionsAuthorized(uris, scopes, registry)` is exported because `subscriptions/listen` is decided at the HTTP boundary, before a request reaches the server instance — so a host that mounts this engine must call it there. Omitting it means a client with any valid token can observe updates for a resource whose scope it was never granted.
|
|
111
133
|
|
|
134
|
+
## Rate limiting and concurrency
|
|
135
|
+
|
|
136
|
+
`@lostgradient/mcp/rate-limit` provides the protocol-level sliding-window policy, in-memory and Redis stores, MCP concurrency slots, and the standard `429` response. The Redis factories accept the `MinimalRedisClient` seam from `@lostgradient/mcp/oauth`; they do not require a particular Redis package or a full client object.
|
|
137
|
+
|
|
138
|
+
The shared `RateLimitConfiguration` owns exactly eight protocol categories: OAuth authorize, registration, token network, token client, and revocation; MCP network and user; and failed authentication. Host-only routes such as sign-in, session creation, health, and metrics should use `SlidingWindowRateLimiter` directly with host-owned categories rather than extending the protocol category union.
|
|
139
|
+
|
|
140
|
+
Concurrency is a resource-lifetime concern, not a handler-promise concern. For a streaming response, pass the acquired slot to `attachConcurrencySlotToResponseLifetime` so it renews while the body remains open and releases only when the body closes, is canceled, or errors. A host that separately tracks requests must follow the same rule; Tribunal's other implementation is `applications/web/src/lib/in-flight-request-tracker.ts`.
|
|
141
|
+
|
|
142
|
+
## Host logging
|
|
143
|
+
|
|
144
|
+
Call `setLogger(hostLogger)` before serving requests to route every engine log record through the host's existing sink and redaction policy. The logger is structural and deliberately small: `info`, `warn`, `error`, and `child`. A host does not need to import pino or implement any other pino API. The exported `logger` and `getLogger()` remain the package's full pino-backed logger for compatibility; injection changes the engine's internal sink. If `setLogger` is not called, engine records use that same lazy pino logger and existing behavior.
|
|
145
|
+
|
|
146
|
+
## Required server identity in 0.2.0
|
|
147
|
+
|
|
148
|
+
`MCP_SERVER_NAME` is required starting in 0.2.0. The package no longer defaults to the template-branded `template-mcp-server` identity because that fallback was silently advertised to every connected MCP client. Set the explicit server name before constructing a server.
|
|
149
|
+
|
|
150
|
+
## Mounting in SvelteKit
|
|
151
|
+
|
|
152
|
+
`@lostgradient/mcp/sveltekit` provides a dependency-free adapter for a SvelteKit `handle` chain. Call `createSvelteKitMcpMount` once in a long-lived server process, pass the OAuth seams and MCP runtime, and delegate each request to the returned `handle`. The adapter claims its process lifecycle synchronously: a second mount fails, disposal is permanent, and failed startup cannot be retried in the same process.
|
|
153
|
+
|
|
154
|
+
The host's identity handle must run first and call `primeSvelteKitMcpIdentity(event, identity)` for every request, including anonymous requests with `null`. The mount rejects a request when that handle was skipped or sequenced after it. It reads `event.getClientAddress()` for each request so the OAuth and MCP serving layers receive the immediate socket peer rather than a construction-time value.
|
|
155
|
+
|
|
156
|
+
The host still owns the network listener, signal handling, request draining, and process termination. It must dispose the mount only after response bodies, including long-lived MCP streams, have closed or been canceled. Request-scoped edge and serverless runtimes cannot preserve the mount's subscriptions and must not set `longLivedProcess` to true. Adapter-node deployment behavior is intentionally left to the first host integration rather than claimed by this package contract.
|
|
157
|
+
|
|
158
|
+
## Client ID Metadata Documents
|
|
159
|
+
|
|
160
|
+
`@lostgradient/mcp/oauth` exports Client ID Metadata Document fetching and the shared OAuth security utilities. Use `safeFetchPublicHttpsUrl` for any client-supplied metadata URL. It applies the complete SSRF boundary as one operation: the URL must use HTTPS, literal private addresses are rejected, every DNS result must be public, and redirects are disabled. Do not recreate those checks at a host call site.
|
|
161
|
+
|
|
162
|
+
The dedicated `@lostgradient/mcp/oauth/client-metadata-documents` subpath exposes the same safe fetch together with `fetchClientIdMetadataDocument` and `isClientIdMetadataDocumentUrl`. The general `/oauth` entry point also owns `isAddressInCidr`, `isValidCidr`, `isValidRedirectUri`, `isValidClientName`, `isExactContentType`, `withDeadline`, and IP canonicalization so an embedding host does not maintain a second security implementation.
|
|
163
|
+
|
|
112
164
|
## Subpaths
|
|
113
165
|
|
|
114
|
-
| Subpath
|
|
115
|
-
|
|
|
116
|
-
| `@lostgradient/mcp`
|
|
117
|
-
| `@lostgradient/mcp/logger`
|
|
118
|
-
| `@lostgradient/mcp/env`
|
|
119
|
-
| `@lostgradient/mcp/environment-schema`
|
|
120
|
-
| `@lostgradient/mcp/metrics`
|
|
121
|
-
| `@lostgradient/mcp/
|
|
166
|
+
| Subpath | Contents |
|
|
167
|
+
| --------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
168
|
+
| `@lostgradient/mcp` | The engine: server factory, registries, scope vocabularies, primitives |
|
|
169
|
+
| `@lostgradient/mcp/logger` | Host logger injection and the lazy default pino logger |
|
|
170
|
+
| `@lostgradient/mcp/env` | `parseMcpServerEnvironment` and `getEnvironment` |
|
|
171
|
+
| `@lostgradient/mcp/environment-schema` | The raw Zod shape, side-effect free |
|
|
172
|
+
| `@lostgradient/mcp/metrics` | The in-process metrics collector |
|
|
173
|
+
| `@lostgradient/mcp/oauth` | OAuth contracts, metadata fetching, and shared security utilities |
|
|
174
|
+
| `@lostgradient/mcp/oauth/stores` | Type-only contracts for durable OAuth storage |
|
|
175
|
+
| `@lostgradient/mcp/oauth/testing` | In-memory OAuth stores for tests |
|
|
176
|
+
| `@lostgradient/mcp/oauth/postgres` | PostgreSQL OAuth store implementations |
|
|
177
|
+
| `@lostgradient/mcp/oauth/client-metadata-documents` | Client ID Metadata Document validation and SSRF-safe fetching |
|
|
178
|
+
| `@lostgradient/mcp/rate-limit` | Sliding-window policy, stores, concurrency slots, and `429` responses |
|
|
179
|
+
| `@lostgradient/mcp/http` | Ordered MCP HTTP serving and per-user handler lifecycle |
|
|
180
|
+
| `@lostgradient/mcp/sveltekit` | Host-agnostic SvelteKit handle-chain mount |
|
|
181
|
+
| `@lostgradient/mcp/version` | The advertised package version |
|
|
122
182
|
|
|
123
183
|
## License
|
|
124
184
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// src/rate-limit/sliding-window-rate-limiter.ts
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
class SlidingWindowRateLimiter {
|
|
5
|
+
nowProvider;
|
|
6
|
+
constructor(nowProvider = () => Date.now()) {
|
|
7
|
+
this.nowProvider = nowProvider;
|
|
8
|
+
}
|
|
9
|
+
async consume(input) {
|
|
10
|
+
const nowMilliseconds = this.nowProvider();
|
|
11
|
+
const windowMilliseconds = input.windowSeconds * 1000;
|
|
12
|
+
const result = await input.atomicStore.consume({
|
|
13
|
+
key: input.key,
|
|
14
|
+
nowMilliseconds,
|
|
15
|
+
windowMilliseconds,
|
|
16
|
+
maximumRequests: input.maximumRequests,
|
|
17
|
+
member: `${nowMilliseconds}-${randomUUID()}`
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
allowed: result.allowed,
|
|
21
|
+
retryAfterSeconds: result.allowed ? 0 : Math.max(1, Math.ceil(result.retryAfterMilliseconds / 1000)),
|
|
22
|
+
remainingRequests: result.remainingRequests
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
async peek(input) {
|
|
26
|
+
return input.atomicStore.peek({
|
|
27
|
+
key: input.key,
|
|
28
|
+
nowMilliseconds: this.nowProvider(),
|
|
29
|
+
windowMilliseconds: input.windowSeconds * 1000
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/rate-limit/request-rate-limiter.ts
|
|
35
|
+
class RequestRateLimiter {
|
|
36
|
+
configuration;
|
|
37
|
+
storeProvider;
|
|
38
|
+
#limiter;
|
|
39
|
+
constructor(configuration, storeProvider, nowProvider) {
|
|
40
|
+
this.configuration = configuration;
|
|
41
|
+
this.storeProvider = storeProvider;
|
|
42
|
+
this.#limiter = new SlidingWindowRateLimiter(nowProvider);
|
|
43
|
+
}
|
|
44
|
+
async consume(category, identifier) {
|
|
45
|
+
const categoryConfiguration = this.configuration.categories[category];
|
|
46
|
+
return this.#limiter.consume({
|
|
47
|
+
key: this.buildKey(category, identifier),
|
|
48
|
+
...categoryConfiguration,
|
|
49
|
+
atomicStore: await this.storeProvider()
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
async peek(category, identifier) {
|
|
53
|
+
return this.#limiter.peek({
|
|
54
|
+
key: this.buildKey(category, identifier),
|
|
55
|
+
windowSeconds: this.configuration.categories[category].windowSeconds,
|
|
56
|
+
atomicStore: await this.storeProvider()
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
buildKey(category, identifier) {
|
|
60
|
+
const namespace = this.configuration.keyNamespace;
|
|
61
|
+
return namespace ? `rate_limit:${namespace}:${category}:${identifier}` : `rate_limit:${category}:${identifier}`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/rate-limit/rate-limit-response.ts
|
|
66
|
+
function createRateLimitedResponse(retryAfterSeconds, headers) {
|
|
67
|
+
return Response.json({ error: "rate_limited", error_description: "Too many requests" }, {
|
|
68
|
+
status: 429,
|
|
69
|
+
headers: { ...headers ?? {}, "Retry-After": String(retryAfterSeconds) }
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export { SlidingWindowRateLimiter, RequestRateLimiter, createRateLimitedResponse };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
mcpServerEnvironmentSchema
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-xcf742mf.js";
|
|
4
4
|
|
|
5
5
|
// src/env.ts
|
|
6
6
|
import { z } from "zod";
|
|
@@ -10,6 +10,9 @@ function parseMcpServerEnvironment(env) {
|
|
|
10
10
|
throw new Error("SKIP_ENV_VALIDATION is not supported. Supply a real environment instead — see .env.example.");
|
|
11
11
|
}
|
|
12
12
|
const presentEntries = Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== undefined && entry[1] !== ""));
|
|
13
|
+
if (!presentEntries.MCP_SERVER_NAME) {
|
|
14
|
+
throw new Error("MCP_SERVER_NAME is required. Set the explicit server name advertised to MCP clients.");
|
|
15
|
+
}
|
|
13
16
|
const environment = mcpServerEnvironmentObject.parse(presentEntries);
|
|
14
17
|
if (environment.NODE_ENV === "production" && environment.LOG_CONTENT_DIAGNOSTICS_UNTIL) {
|
|
15
18
|
throw new Error("LOG_CONTENT_DIAGNOSTICS_UNTIL is not supported in production. Raw prompt content logging cannot run in production.");
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import {
|
|
2
|
+
RequestRateLimiter,
|
|
3
|
+
SlidingWindowRateLimiter,
|
|
4
|
+
createRateLimitedResponse
|
|
5
|
+
} from "./chunk-3ek3knfm.js";
|
|
6
|
+
|
|
7
|
+
// src/rate-limit/in-memory-sliding-window-store.ts
|
|
8
|
+
function createInMemorySlidingWindowStore() {
|
|
9
|
+
const membersByKey = new Map;
|
|
10
|
+
const expirationsByKey = new Map;
|
|
11
|
+
const pruneExpired = (key, nowMilliseconds, cutoffScore) => {
|
|
12
|
+
const expiresAt = expirationsByKey.get(key);
|
|
13
|
+
if (expiresAt !== undefined && nowMilliseconds > expiresAt) {
|
|
14
|
+
membersByKey.delete(key);
|
|
15
|
+
expirationsByKey.delete(key);
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
const remaining = (membersByKey.get(key) ?? []).filter((entry) => entry.score > cutoffScore);
|
|
19
|
+
membersByKey.set(key, remaining);
|
|
20
|
+
return remaining;
|
|
21
|
+
};
|
|
22
|
+
return {
|
|
23
|
+
consume: async (input) => {
|
|
24
|
+
const existing = pruneExpired(input.key, input.nowMilliseconds, input.nowMilliseconds - input.windowMilliseconds);
|
|
25
|
+
if (existing.length >= input.maximumRequests) {
|
|
26
|
+
const oldest = existing.reduce((minimum, entry) => entry.score < minimum.score ? entry : minimum);
|
|
27
|
+
return {
|
|
28
|
+
allowed: false,
|
|
29
|
+
retryAfterMilliseconds: Math.max(0, oldest.score + input.windowMilliseconds - input.nowMilliseconds),
|
|
30
|
+
remainingRequests: 0
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
existing.push({ score: input.nowMilliseconds, member: input.member });
|
|
34
|
+
membersByKey.set(input.key, existing);
|
|
35
|
+
expirationsByKey.set(input.key, input.nowMilliseconds + input.windowMilliseconds);
|
|
36
|
+
return {
|
|
37
|
+
allowed: true,
|
|
38
|
+
retryAfterMilliseconds: 0,
|
|
39
|
+
remainingRequests: Math.max(0, input.maximumRequests - existing.length)
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
peek: async (input) => pruneExpired(input.key, input.nowMilliseconds, input.nowMilliseconds - input.windowMilliseconds).length
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
var inMemorySlidingWindowStore = createInMemorySlidingWindowStore();
|
|
46
|
+
|
|
47
|
+
// src/rate-limit/mcp-concurrency-limiter.ts
|
|
48
|
+
import { randomUUID } from "node:crypto";
|
|
49
|
+
var DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS = 60000;
|
|
50
|
+
var DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS = 20000;
|
|
51
|
+
var acquireScript = `
|
|
52
|
+
local key = KEYS[1]
|
|
53
|
+
local now_ms = tonumber(ARGV[1])
|
|
54
|
+
local ttl_ms = tonumber(ARGV[2])
|
|
55
|
+
local max_concurrent = tonumber(ARGV[3])
|
|
56
|
+
local member = ARGV[4]
|
|
57
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', now_ms)
|
|
58
|
+
local count = redis.call('ZCARD', key)
|
|
59
|
+
if count >= max_concurrent then return 0 end
|
|
60
|
+
redis.call('ZADD', key, now_ms + ttl_ms, member)
|
|
61
|
+
redis.call('PEXPIRE', key, ttl_ms)
|
|
62
|
+
return 1
|
|
63
|
+
`;
|
|
64
|
+
var renewScript = `
|
|
65
|
+
local key = KEYS[1]
|
|
66
|
+
local now_ms = tonumber(ARGV[1])
|
|
67
|
+
local ttl_ms = tonumber(ARGV[2])
|
|
68
|
+
local member = ARGV[3]
|
|
69
|
+
if redis.call('ZSCORE', key, member) == false then return 0 end
|
|
70
|
+
redis.call('ZADD', key, now_ms + ttl_ms, member)
|
|
71
|
+
redis.call('PEXPIRE', key, ttl_ms)
|
|
72
|
+
return 1
|
|
73
|
+
`;
|
|
74
|
+
function createRedisConcurrencySlotStore(redisClient, providers = {}) {
|
|
75
|
+
const now = providers.now ?? (() => Date.now());
|
|
76
|
+
const createId = providers.createId ?? randomUUID;
|
|
77
|
+
return {
|
|
78
|
+
acquire: async (key, maximumConcurrent, ttlMilliseconds) => {
|
|
79
|
+
const slot = { id: createId() };
|
|
80
|
+
const reply = await redisClient.eval(acquireScript, {
|
|
81
|
+
keys: [key],
|
|
82
|
+
arguments: [String(now()), String(ttlMilliseconds), String(maximumConcurrent), slot.id]
|
|
83
|
+
});
|
|
84
|
+
return reply === 1 ? slot : null;
|
|
85
|
+
},
|
|
86
|
+
renew: async (key, slot, ttlMilliseconds) => await redisClient.eval(renewScript, {
|
|
87
|
+
keys: [key],
|
|
88
|
+
arguments: [String(now()), String(ttlMilliseconds), slot.id]
|
|
89
|
+
}) === 1,
|
|
90
|
+
release: async (key, slot) => {
|
|
91
|
+
await redisClient.zRem(key, slot.id);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function createInMemoryConcurrencySlotStore() {
|
|
96
|
+
const slotsByKey = new Map;
|
|
97
|
+
return {
|
|
98
|
+
acquire: async (key, maximumConcurrent) => {
|
|
99
|
+
const slots = slotsByKey.get(key) ?? new Set;
|
|
100
|
+
if (slots.size >= maximumConcurrent)
|
|
101
|
+
return null;
|
|
102
|
+
const slot = { id: randomUUID() };
|
|
103
|
+
slots.add(slot.id);
|
|
104
|
+
slotsByKey.set(key, slots);
|
|
105
|
+
return slot;
|
|
106
|
+
},
|
|
107
|
+
renew: async (key, slot) => slotsByKey.get(key)?.has(slot.id) ?? false,
|
|
108
|
+
release: async (key, slot) => {
|
|
109
|
+
slotsByKey.get(key)?.delete(slot.id);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
class McpConcurrencyLimiter {
|
|
115
|
+
store;
|
|
116
|
+
maximumConcurrent;
|
|
117
|
+
ttlMilliseconds;
|
|
118
|
+
onStoreError;
|
|
119
|
+
constructor(store, maximumConcurrent, ttlMilliseconds = DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS, onStoreError = () => {}) {
|
|
120
|
+
this.store = store;
|
|
121
|
+
this.maximumConcurrent = maximumConcurrent;
|
|
122
|
+
this.ttlMilliseconds = ttlMilliseconds;
|
|
123
|
+
this.onStoreError = onStoreError;
|
|
124
|
+
}
|
|
125
|
+
async acquire(key) {
|
|
126
|
+
const slot = await this.store.acquire(key, this.maximumConcurrent, this.ttlMilliseconds);
|
|
127
|
+
let released = false;
|
|
128
|
+
return {
|
|
129
|
+
allowed: slot !== null,
|
|
130
|
+
renewalIntervalMilliseconds: Math.max(1, Math.floor(this.ttlMilliseconds / 3)),
|
|
131
|
+
release: async () => {
|
|
132
|
+
if (!slot || released)
|
|
133
|
+
return;
|
|
134
|
+
released = true;
|
|
135
|
+
try {
|
|
136
|
+
await this.store.release(key, slot);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
this.onStoreError(error, "release");
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
renew: async () => {
|
|
142
|
+
if (!slot || released)
|
|
143
|
+
return;
|
|
144
|
+
try {
|
|
145
|
+
await this.store.renew(key, slot, this.ttlMilliseconds);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
this.onStoreError(error, "renew");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function attachConcurrencySlotToResponseLifetime(response, slot, renewalIntervalMilliseconds = slot.renewalIntervalMilliseconds ?? DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS) {
|
|
154
|
+
if (!response.body || response.bodyUsed) {
|
|
155
|
+
slot.release();
|
|
156
|
+
return response;
|
|
157
|
+
}
|
|
158
|
+
let settled = false;
|
|
159
|
+
const renewalTimer = setInterval(() => void slot.renew(), renewalIntervalMilliseconds);
|
|
160
|
+
renewalTimer.unref?.();
|
|
161
|
+
const settleOnce = () => {
|
|
162
|
+
if (settled)
|
|
163
|
+
return;
|
|
164
|
+
settled = true;
|
|
165
|
+
clearInterval(renewalTimer);
|
|
166
|
+
slot.release();
|
|
167
|
+
};
|
|
168
|
+
const sourceReader = response.body.getReader();
|
|
169
|
+
const trackedBody = new ReadableStream({
|
|
170
|
+
async pull(controller) {
|
|
171
|
+
try {
|
|
172
|
+
const { done, value } = await sourceReader.read();
|
|
173
|
+
if (done) {
|
|
174
|
+
controller.close();
|
|
175
|
+
settleOnce();
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
controller.enqueue(value);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
controller.error(error);
|
|
181
|
+
settleOnce();
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
cancel(reason) {
|
|
185
|
+
sourceReader.cancel(reason).catch(() => {});
|
|
186
|
+
settleOnce();
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
return new Response(trackedBody, {
|
|
190
|
+
status: response.status,
|
|
191
|
+
statusText: response.statusText,
|
|
192
|
+
headers: response.headers
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/rate-limit/redis-sliding-window-store.ts
|
|
197
|
+
var consumeScript = `
|
|
198
|
+
local key = KEYS[1]
|
|
199
|
+
local now = tonumber(ARGV[1])
|
|
200
|
+
local window = tonumber(ARGV[2])
|
|
201
|
+
local max_requests = tonumber(ARGV[3])
|
|
202
|
+
local member = ARGV[4]
|
|
203
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
|
|
204
|
+
local count = redis.call('ZCARD', key)
|
|
205
|
+
if count >= max_requests then
|
|
206
|
+
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
|
|
207
|
+
local retry_after = window
|
|
208
|
+
if oldest[2] ~= nil then
|
|
209
|
+
retry_after = tonumber(oldest[2]) + window - now
|
|
210
|
+
if retry_after < 0 then retry_after = 0 end
|
|
211
|
+
end
|
|
212
|
+
return {0, retry_after, 0}
|
|
213
|
+
end
|
|
214
|
+
redis.call('ZADD', key, now, member)
|
|
215
|
+
redis.call('PEXPIRE', key, window)
|
|
216
|
+
return {1, 0, max_requests - count - 1}
|
|
217
|
+
`;
|
|
218
|
+
var peekScript = `
|
|
219
|
+
local key = KEYS[1]
|
|
220
|
+
local now = tonumber(ARGV[1])
|
|
221
|
+
local window = tonumber(ARGV[2])
|
|
222
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
|
|
223
|
+
return redis.call('ZCARD', key)
|
|
224
|
+
`;
|
|
225
|
+
function serializeFiniteScriptArgument(value, parameterName) {
|
|
226
|
+
if (!Number.isFinite(value)) {
|
|
227
|
+
throw new TypeError(`Rate limiter received a non-finite ${parameterName} (${String(value)}). ` + "This indicates missing or unparsed rate-limit configuration, not a Redis fault.");
|
|
228
|
+
}
|
|
229
|
+
return String(value);
|
|
230
|
+
}
|
|
231
|
+
function createRedisSlidingWindowStore(redisClient) {
|
|
232
|
+
return {
|
|
233
|
+
consume: async (input) => {
|
|
234
|
+
const reply = await redisClient.eval(consumeScript, {
|
|
235
|
+
keys: [input.key],
|
|
236
|
+
arguments: [
|
|
237
|
+
serializeFiniteScriptArgument(input.nowMilliseconds, "nowMilliseconds"),
|
|
238
|
+
serializeFiniteScriptArgument(input.windowMilliseconds, "windowMilliseconds"),
|
|
239
|
+
serializeFiniteScriptArgument(input.maximumRequests, "maximumRequests"),
|
|
240
|
+
input.member
|
|
241
|
+
]
|
|
242
|
+
});
|
|
243
|
+
return {
|
|
244
|
+
allowed: reply[0] === 1,
|
|
245
|
+
retryAfterMilliseconds: Number(reply[1]),
|
|
246
|
+
remainingRequests: Number(reply[2])
|
|
247
|
+
};
|
|
248
|
+
},
|
|
249
|
+
peek: async (input) => Number(await redisClient.eval(peekScript, {
|
|
250
|
+
keys: [input.key],
|
|
251
|
+
arguments: [
|
|
252
|
+
serializeFiniteScriptArgument(input.nowMilliseconds, "nowMilliseconds"),
|
|
253
|
+
serializeFiniteScriptArgument(input.windowMilliseconds, "windowMilliseconds")
|
|
254
|
+
]
|
|
255
|
+
}))
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/rate-limit/index.ts
|
|
260
|
+
var attachConcurrencySlotToResponseLifetime2 = attachConcurrencySlotToResponseLifetime;
|
|
261
|
+
var createInMemoryConcurrencySlotStore2 = createInMemoryConcurrencySlotStore;
|
|
262
|
+
var createInMemorySlidingWindowStore2 = createInMemorySlidingWindowStore;
|
|
263
|
+
var createRateLimitedResponse2 = createRateLimitedResponse;
|
|
264
|
+
var createRedisConcurrencySlotStore2 = createRedisConcurrencySlotStore;
|
|
265
|
+
var createRedisSlidingWindowStore2 = createRedisSlidingWindowStore;
|
|
266
|
+
var DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS2 = DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS;
|
|
267
|
+
var DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS2 = DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS;
|
|
268
|
+
var inMemorySlidingWindowStore2 = inMemorySlidingWindowStore;
|
|
269
|
+
var McpConcurrencyLimiter2 = McpConcurrencyLimiter;
|
|
270
|
+
var RequestRateLimiter2 = RequestRateLimiter;
|
|
271
|
+
var SlidingWindowRateLimiter2 = SlidingWindowRateLimiter;
|
|
272
|
+
|
|
273
|
+
export { attachConcurrencySlotToResponseLifetime2 as attachConcurrencySlotToResponseLifetime, createInMemoryConcurrencySlotStore2 as createInMemoryConcurrencySlotStore, createInMemorySlidingWindowStore2 as createInMemorySlidingWindowStore, createRateLimitedResponse2 as createRateLimitedResponse, createRedisConcurrencySlotStore2 as createRedisConcurrencySlotStore, createRedisSlidingWindowStore2 as createRedisSlidingWindowStore, DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS2 as DEFAULT_CONCURRENCY_SLOT_RENEWAL_INTERVAL_MILLISECONDS, DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS2 as DEFAULT_CONCURRENCY_SLOT_TTL_MILLISECONDS, inMemorySlidingWindowStore2 as inMemorySlidingWindowStore, McpConcurrencyLimiter2 as McpConcurrencyLimiter, RequestRateLimiter2 as RequestRateLimiter, SlidingWindowRateLimiter2 as SlidingWindowRateLimiter };
|