@nest-mcp/core 0.0.0-stage → 2.0.0-alpha.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.
- package/CHANGELOG.md +7 -0
- package/LICENSE +28 -0
- package/README.md +111 -2
- package/dist/attribute-values-BO6aCUgL.mjs +25 -0
- package/dist/attribute-values-BO6aCUgL.mjs.map +1 -0
- package/dist/authorization.d.mts +50 -0
- package/dist/authorization.d.mts.map +1 -0
- package/dist/authorization.mjs +113 -0
- package/dist/authorization.mjs.map +1 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +5 -0
- package/dist/lifecycle.d.mts +58 -0
- package/dist/lifecycle.d.mts.map +1 -0
- package/dist/lifecycle.mjs +116 -0
- package/dist/lifecycle.mjs.map +1 -0
- package/dist/middleware.d.mts +32 -0
- package/dist/middleware.d.mts.map +1 -0
- package/dist/middleware.mjs +58 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/operation-D33Ttxve.d.mts +71 -0
- package/dist/operation-D33Ttxve.d.mts.map +1 -0
- package/dist/operation.d.mts +2 -0
- package/dist/operation.mjs +57 -0
- package/dist/operation.mjs.map +1 -0
- package/package.json +79 -3
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, btwld
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nest-mcp/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-neutral runtime primitives for building MCP clients, servers, gateways, and NestJS adapters. This package deliberately has no dependency on NestJS or an MCP SDK; adapters translate their SDK-specific calls into these stable operation primitives.
|
|
4
|
+
|
|
5
|
+
## What it provides
|
|
6
|
+
|
|
7
|
+
- Immutable operation context and metadata with correlation, cancellation, principal, and attribute propagation.
|
|
8
|
+
- Onion-style middleware composition with concurrent invocation safety and a guard against calling `next()` twice.
|
|
9
|
+
- Result-opaque passthrough middleware for observers that must preserve the exact downstream value.
|
|
10
|
+
- Explicit allow/deny authorization decisions, fail-closed enforcement, and reusable authorization middleware.
|
|
11
|
+
- Structured started, succeeded, failed, and cancelled lifecycle events.
|
|
12
|
+
- Best-effort telemetry middleware that never replaces the operation result or its primary error.
|
|
13
|
+
- Observer fan-out that attempts every observer and reports aggregate failures.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add @nest-mcp/core
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Compose an operation pipeline
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import {
|
|
25
|
+
allowMcpOperation,
|
|
26
|
+
composeMcpLifecycleObservers,
|
|
27
|
+
composeMcpMiddleware,
|
|
28
|
+
createMcpAuthorizationMiddleware,
|
|
29
|
+
createMcpLifecycleMiddleware,
|
|
30
|
+
createMcpOperation,
|
|
31
|
+
createMcpOperationContext,
|
|
32
|
+
type McpAuthorizationPolicy,
|
|
33
|
+
} from "@nest-mcp/core";
|
|
34
|
+
|
|
35
|
+
const telemetry = composeMcpLifecycleObservers([
|
|
36
|
+
{
|
|
37
|
+
onEvent(event) {
|
|
38
|
+
console.info(event.type, event.context.operationId);
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
const policy: McpAuthorizationPolicy<{ tool: string }> = {
|
|
44
|
+
authorize(operation) {
|
|
45
|
+
return operation.context.principal === undefined
|
|
46
|
+
? { effect: "deny", reason: "Authentication is required.", attributes: {} }
|
|
47
|
+
: allowMcpOperation({ policy: "authenticated-tools" });
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const execute = composeMcpMiddleware(
|
|
52
|
+
[
|
|
53
|
+
createMcpLifecycleMiddleware(telemetry, {
|
|
54
|
+
onObserverError(error) {
|
|
55
|
+
console.error("Telemetry failed", error);
|
|
56
|
+
},
|
|
57
|
+
}),
|
|
58
|
+
createMcpAuthorizationMiddleware(policy),
|
|
59
|
+
],
|
|
60
|
+
async ({ input }) => ({ content: `Called ${input.tool}` }),
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const context = createMcpOperationContext({
|
|
64
|
+
operationId: crypto.randomUUID(),
|
|
65
|
+
role: "gateway",
|
|
66
|
+
operation: {
|
|
67
|
+
name: "tools/call",
|
|
68
|
+
kind: "request",
|
|
69
|
+
capability: "tools",
|
|
70
|
+
target: "weather-server",
|
|
71
|
+
},
|
|
72
|
+
principal: { subject: "user-123" },
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const result = await execute(createMcpOperation({ tool: "weather" }, context));
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Middleware is entered from left to right and unwinds from right to left. A middleware continuation may be called at most once. Keep lifecycle middleware outside authorization middleware when denied attempts should produce failure telemetry.
|
|
79
|
+
|
|
80
|
+
For logging, tracing, rate limits, and similar concerns that should never transform a protocol result,
|
|
81
|
+
wrap a result-opaque callback with `createMcpPassthroughMiddleware`. Its `next()` resolves to `void`;
|
|
82
|
+
the adapter retains and returns the exact downstream value, requires the callback to continue, and
|
|
83
|
+
does not allow a swallowed downstream failure to become a successful result.
|
|
84
|
+
|
|
85
|
+
## Authorization is fail closed
|
|
86
|
+
|
|
87
|
+
`enforceMcpAuthorization` returns only an explicit, structurally valid allow decision. It raises `McpAuthorizationError` when:
|
|
88
|
+
|
|
89
|
+
- no policy is configured;
|
|
90
|
+
- the policy throws or rejects;
|
|
91
|
+
- the policy returns a malformed value; or
|
|
92
|
+
- the policy explicitly denies the operation.
|
|
93
|
+
|
|
94
|
+
The error has the stable code `MCP_AUTHORIZATION_DENIED`, a `failure` classification, the operation ID, and the deny decision. Policy exceptions are retained as the error `cause` but are not included in the public error message.
|
|
95
|
+
|
|
96
|
+
## Lifecycle and telemetry behavior
|
|
97
|
+
|
|
98
|
+
Lifecycle events contain context, timestamps, duration, and sanitized error details. They intentionally do not contain operation inputs or outputs, which reduces accidental payload or credential leakage.
|
|
99
|
+
|
|
100
|
+
The lifecycle middleware treats observers as best-effort: observer failures may be routed to `onObserverError`, but neither observer nor observer-error-handler failures replace an operation result or its primary error. `composeMcpLifecycleObservers` itself surfaces failures after attempting every observer, allowing it to remain useful outside the middleware.
|
|
101
|
+
|
|
102
|
+
## Entry points
|
|
103
|
+
|
|
104
|
+
- `@nest-mcp/core`
|
|
105
|
+
- `@nest-mcp/core/operation`
|
|
106
|
+
- `@nest-mcp/core/middleware`
|
|
107
|
+
- `@nest-mcp/core/authorization`
|
|
108
|
+
- `@nest-mcp/core/lifecycle`
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
BSD-3-Clause
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/attribute-values.ts
|
|
2
|
+
function copyMcpAttributes(attributes, name = "attributes") {
|
|
3
|
+
if (attributes === void 0) return Object.freeze({});
|
|
4
|
+
if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes)) throw new TypeError(`${name} must be a record.`);
|
|
5
|
+
const copy = {};
|
|
6
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
7
|
+
if (isAttributeScalar(value)) {
|
|
8
|
+
copy[key] = value;
|
|
9
|
+
continue;
|
|
10
|
+
}
|
|
11
|
+
if (Array.isArray(value) && value.every(isAttributeScalar)) {
|
|
12
|
+
copy[key] = Object.freeze([...value]);
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
throw new TypeError(`${name}.${key} must be a scalar or scalar array.`);
|
|
16
|
+
}
|
|
17
|
+
return Object.freeze(copy);
|
|
18
|
+
}
|
|
19
|
+
function isAttributeScalar(value) {
|
|
20
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { copyMcpAttributes as t };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=attribute-values-BO6aCUgL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attribute-values-BO6aCUgL.mjs","names":[],"sources":["../src/attribute-values.ts"],"sourcesContent":["export type McpAttributeScalar = string | number | boolean;\n\n/** Immutable, telemetry-compatible operation dimension. */\nexport type McpAttributeValue = McpAttributeScalar | readonly McpAttributeScalar[];\n\n/** Low-cardinality dimensions safe to attach to operation and telemetry context. */\nexport type McpAttributes = Readonly<Record<string, McpAttributeValue>>;\n\nexport function copyMcpAttributes(attributes: unknown, name = \"attributes\"): McpAttributes {\n\tif (attributes === undefined) return Object.freeze({});\n\tif (typeof attributes !== \"object\" || attributes === null || Array.isArray(attributes)) {\n\t\tthrow new TypeError(`${name} must be a record.`);\n\t}\n\tconst copy: Record<string, McpAttributeValue> = {};\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (isAttributeScalar(value)) {\n\t\t\tcopy[key] = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(value) && value.every(isAttributeScalar)) {\n\t\t\tcopy[key] = Object.freeze([...value]);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`${name}.${key} must be a scalar or scalar array.`);\n\t}\n\treturn Object.freeze(copy);\n}\n\nfunction isAttributeScalar(value: unknown): value is McpAttributeScalar {\n\treturn (\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\" ||\n\t\t(typeof value === \"number\" && Number.isFinite(value))\n\t);\n}\n"],"mappings":";AAQA,SAAgB,kBAAkB,YAAqB,OAAO,cAA6B;CAC1F,IAAI,eAAe,KAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC;CACrD,IAAI,OAAO,eAAe,YAAY,eAAe,QAAQ,MAAM,QAAQ,UAAU,GACpF,MAAM,IAAI,UAAU,GAAG,KAAK,mBAAmB;CAEhD,MAAM,OAA0C,CAAC;CACjD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAAG;EACtD,IAAI,kBAAkB,KAAK,GAAG;GAC7B,KAAK,OAAO;GACZ;EACD;EACA,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,iBAAiB,GAAG;GAC3D,KAAK,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;GACpC;EACD;EACA,MAAM,IAAI,UAAU,GAAG,KAAK,GAAG,IAAI,mCAAmC;CACvE;CACA,OAAO,OAAO,OAAO,IAAI;AAC1B;AAEA,SAAS,kBAAkB,OAA6C;CACvE,OACC,OAAO,UAAU,YACjB,OAAO,UAAU,aAChB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAErD"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { c as McpOperationMiddleware, h as McpAttributes, n as McpOperation, r as McpOperationContext, t as MaybePromise } from "./operation-D33Ttxve.mjs";
|
|
2
|
+
//#region src/authorization.d.ts
|
|
3
|
+
declare const MCP_AUTHORIZATION_DENIED: "MCP_AUTHORIZATION_DENIED";
|
|
4
|
+
interface McpAuthorizationAllowDecision {
|
|
5
|
+
readonly effect: "allow";
|
|
6
|
+
readonly policy?: string;
|
|
7
|
+
readonly reason?: string;
|
|
8
|
+
readonly attributes: McpAttributes;
|
|
9
|
+
}
|
|
10
|
+
interface McpAuthorizationDenyDecision {
|
|
11
|
+
readonly effect: "deny";
|
|
12
|
+
readonly policy?: string;
|
|
13
|
+
readonly reason: string;
|
|
14
|
+
readonly attributes: McpAttributes;
|
|
15
|
+
}
|
|
16
|
+
/** Explicit authorization result. Missing or malformed results are never treated as allow. */
|
|
17
|
+
type McpAuthorizationDecision = McpAuthorizationAllowDecision | McpAuthorizationDenyDecision;
|
|
18
|
+
/** Framework-neutral policy evaluated against the complete operation envelope. */
|
|
19
|
+
interface McpAuthorizationPolicy<Input = unknown, Context extends McpOperationContext = McpOperationContext> {
|
|
20
|
+
authorize(operation: McpOperation<Input, Context>): MaybePromise<McpAuthorizationDecision>;
|
|
21
|
+
}
|
|
22
|
+
interface McpAuthorizationDecisionInit {
|
|
23
|
+
readonly policy?: string;
|
|
24
|
+
readonly reason?: string;
|
|
25
|
+
readonly attributes?: McpAttributes;
|
|
26
|
+
}
|
|
27
|
+
type McpAuthorizationFailure = "denied" | "missing-policy" | "invalid-decision" | "policy-error";
|
|
28
|
+
/** Fail-closed error raised before a denied operation reaches its terminal handler. */
|
|
29
|
+
declare class McpAuthorizationError extends Error {
|
|
30
|
+
readonly code: "MCP_AUTHORIZATION_DENIED";
|
|
31
|
+
readonly failure: McpAuthorizationFailure;
|
|
32
|
+
readonly operationId: string;
|
|
33
|
+
readonly decision: McpAuthorizationDenyDecision;
|
|
34
|
+
constructor(operation: McpOperation, decision: McpAuthorizationDenyDecision, failure: McpAuthorizationFailure, options?: ErrorOptions);
|
|
35
|
+
}
|
|
36
|
+
/** Constructs a frozen allow decision. */
|
|
37
|
+
declare function allowMcpOperation(init?: McpAuthorizationDecisionInit): McpAuthorizationAllowDecision;
|
|
38
|
+
/** Constructs a frozen deny decision with a required, non-empty reason. */
|
|
39
|
+
declare function denyMcpOperation(reason: string, init?: Omit<McpAuthorizationDecisionInit, "reason">): McpAuthorizationDenyDecision;
|
|
40
|
+
/**
|
|
41
|
+
* Evaluates a policy and returns only an explicit allow. A missing policy,
|
|
42
|
+
* policy exception, malformed result, or deny decision raises
|
|
43
|
+
* `McpAuthorizationError` and therefore fails closed.
|
|
44
|
+
*/
|
|
45
|
+
declare function enforceMcpAuthorization<Input, Context extends McpOperationContext = McpOperationContext>(policy: McpAuthorizationPolicy<Input, Context> | undefined, operation: McpOperation<Input, Context>): Promise<McpAuthorizationAllowDecision>;
|
|
46
|
+
/** Creates middleware that enforces authorization before invoking the next stage. */
|
|
47
|
+
declare function createMcpAuthorizationMiddleware<Input, Output, Context extends McpOperationContext = McpOperationContext>(policy: McpAuthorizationPolicy<Input, Context> | undefined): McpOperationMiddleware<Input, Output, Context>;
|
|
48
|
+
//#endregion
|
|
49
|
+
export { MCP_AUTHORIZATION_DENIED, McpAuthorizationAllowDecision, McpAuthorizationDecision, McpAuthorizationDecisionInit, McpAuthorizationDenyDecision, McpAuthorizationError, McpAuthorizationFailure, McpAuthorizationPolicy, allowMcpOperation, createMcpAuthorizationMiddleware, denyMcpOperation, enforceMcpAuthorization };
|
|
50
|
+
//# sourceMappingURL=authorization.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorization.d.mts","names":[],"sources":["../src/authorization.ts"],"mappings":";;cASa;UAEI;WACP;WACA;WACA;WACA,YAAY;;UAGL;WACP;WACA;WACA;WACA,YAAY;;;KAIV,2BAA2B,gCAAgC;;UAGtD,uBAChB,iBACA,gBAAgB,sBAAsB;EAEtC,UAAU,WAAW,aAAa,OAAO,WAAW,aAAa;;UAGjD;WACP;WACA;WACA,aAAa;;KAGX;;cAIC,8BAA8B;WACjC;WACA,SAAS;WACT;WACA,UAAU;EAEnB,YACC,WAAW,cACX,UAAU,8BACV,SAAS,yBACT,UAAU;;;iBAWI,kBACf,OAAM,+BACJ;;iBAYa,iBACf,gBACA,OAAM,KAAK,0CACT;;;;;;iBAgBmB,wBACrB,OACA,gBAAgB,sBAAsB,qBAEtC,QAAQ,uBAAuB,OAAO,sBACtC,WAAW,aAAa,OAAO,WAC7B,QAAQ;;iBAiDK,iCACf,OACA,QACA,gBAAgB,sBAAsB,qBAEtC,QAAQ,uBAAuB,OAAO,uBACpC,uBAAuB,OAAO,QAAQ"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { t as copyMcpAttributes } from "./attribute-values-BO6aCUgL.mjs";
|
|
2
|
+
//#region src/authorization.ts
|
|
3
|
+
const MCP_AUTHORIZATION_DENIED = "MCP_AUTHORIZATION_DENIED";
|
|
4
|
+
/** Fail-closed error raised before a denied operation reaches its terminal handler. */
|
|
5
|
+
var McpAuthorizationError = class extends Error {
|
|
6
|
+
code = MCP_AUTHORIZATION_DENIED;
|
|
7
|
+
failure;
|
|
8
|
+
operationId;
|
|
9
|
+
decision;
|
|
10
|
+
constructor(operation, decision, failure, options) {
|
|
11
|
+
super("MCP operation authorization was denied.", options);
|
|
12
|
+
this.name = "McpAuthorizationError";
|
|
13
|
+
this.failure = failure;
|
|
14
|
+
this.operationId = operation.context.operationId;
|
|
15
|
+
this.decision = decision;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** Constructs a frozen allow decision. */
|
|
19
|
+
function allowMcpOperation(init = {}) {
|
|
20
|
+
assertOptionalNonEmpty(init.policy, "policy");
|
|
21
|
+
assertOptionalNonEmpty(init.reason, "reason");
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
effect: "allow",
|
|
24
|
+
...init.policy === void 0 ? {} : { policy: init.policy },
|
|
25
|
+
...init.reason === void 0 ? {} : { reason: init.reason },
|
|
26
|
+
attributes: copyMcpAttributes(init.attributes)
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** Constructs a frozen deny decision with a required, non-empty reason. */
|
|
30
|
+
function denyMcpOperation(reason, init = {}) {
|
|
31
|
+
assertNonEmpty(reason, "reason");
|
|
32
|
+
assertOptionalNonEmpty(init.policy, "policy");
|
|
33
|
+
return Object.freeze({
|
|
34
|
+
effect: "deny",
|
|
35
|
+
...init.policy === void 0 ? {} : { policy: init.policy },
|
|
36
|
+
reason,
|
|
37
|
+
attributes: copyMcpAttributes(init.attributes)
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Evaluates a policy and returns only an explicit allow. A missing policy,
|
|
42
|
+
* policy exception, malformed result, or deny decision raises
|
|
43
|
+
* `McpAuthorizationError` and therefore fails closed.
|
|
44
|
+
*/
|
|
45
|
+
async function enforceMcpAuthorization(policy, operation) {
|
|
46
|
+
if (policy === void 0) throw authorizationError(operation, denyMcpOperation("No authorization policy is configured."), "missing-policy");
|
|
47
|
+
let decision;
|
|
48
|
+
try {
|
|
49
|
+
decision = await policy.authorize(operation);
|
|
50
|
+
} catch (cause) {
|
|
51
|
+
throw authorizationError(operation, denyMcpOperation("The authorization policy failed."), "policy-error", { cause });
|
|
52
|
+
}
|
|
53
|
+
let normalizedDecision;
|
|
54
|
+
try {
|
|
55
|
+
normalizedDecision = normalizeAuthorizationDecision(decision);
|
|
56
|
+
} catch (cause) {
|
|
57
|
+
throw authorizationError(operation, denyMcpOperation("The authorization policy returned an invalid decision."), "invalid-decision", { cause });
|
|
58
|
+
}
|
|
59
|
+
if (normalizedDecision === void 0) throw authorizationError(operation, denyMcpOperation("The authorization policy returned an invalid decision."), "invalid-decision");
|
|
60
|
+
if (normalizedDecision.effect === "deny") throw authorizationError(operation, normalizedDecision, "denied");
|
|
61
|
+
return normalizedDecision;
|
|
62
|
+
}
|
|
63
|
+
/** Creates middleware that enforces authorization before invoking the next stage. */
|
|
64
|
+
function createMcpAuthorizationMiddleware(policy) {
|
|
65
|
+
return async (operation, next) => {
|
|
66
|
+
await enforceMcpAuthorization(policy, operation);
|
|
67
|
+
return next();
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function normalizeAuthorizationDecision(value) {
|
|
71
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
72
|
+
const candidate = value;
|
|
73
|
+
if (candidate.effect !== "allow" && candidate.effect !== "deny") return void 0;
|
|
74
|
+
if (!isAttributes(candidate.attributes)) return void 0;
|
|
75
|
+
if (!isOptionalNonEmpty(candidate.policy)) return void 0;
|
|
76
|
+
if (candidate.effect === "deny") {
|
|
77
|
+
if (typeof candidate.reason !== "string" || candidate.reason.trim().length === 0) return;
|
|
78
|
+
return denyMcpOperation(candidate.reason, {
|
|
79
|
+
...candidate.policy === void 0 ? {} : { policy: candidate.policy },
|
|
80
|
+
attributes: candidate.attributes
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
if (!isOptionalNonEmpty(candidate.reason)) return void 0;
|
|
84
|
+
return allowMcpOperation({
|
|
85
|
+
...candidate.policy === void 0 ? {} : { policy: candidate.policy },
|
|
86
|
+
...candidate.reason === void 0 ? {} : { reason: candidate.reason },
|
|
87
|
+
attributes: candidate.attributes
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function authorizationError(operation, decision, failure, options) {
|
|
91
|
+
return new McpAuthorizationError(operation, decision, failure, options);
|
|
92
|
+
}
|
|
93
|
+
function isAttributes(value) {
|
|
94
|
+
try {
|
|
95
|
+
copyMcpAttributes(value);
|
|
96
|
+
return true;
|
|
97
|
+
} catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function isOptionalNonEmpty(value) {
|
|
102
|
+
return value === void 0 || typeof value === "string" && value.trim().length > 0;
|
|
103
|
+
}
|
|
104
|
+
function assertNonEmpty(value, field) {
|
|
105
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${field} must be a non-empty string.`);
|
|
106
|
+
}
|
|
107
|
+
function assertOptionalNonEmpty(value, field) {
|
|
108
|
+
if (value !== void 0) assertNonEmpty(value, field);
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
export { MCP_AUTHORIZATION_DENIED, McpAuthorizationError, allowMcpOperation, createMcpAuthorizationMiddleware, denyMcpOperation, enforceMcpAuthorization };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=authorization.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorization.mjs","names":[],"sources":["../src/authorization.ts"],"sourcesContent":["import type {\n\tMcpOperation,\n\tMcpOperationContext,\n\tMcpOperationMiddleware,\n\tMaybePromise,\n} from \"./operation.ts\";\nimport { copyMcpAttributes } from \"./attribute-values.ts\";\nimport type { McpAttributes } from \"./attribute-values.ts\";\n\nexport const MCP_AUTHORIZATION_DENIED = \"MCP_AUTHORIZATION_DENIED\" as const;\n\nexport interface McpAuthorizationAllowDecision {\n\treadonly effect: \"allow\";\n\treadonly policy?: string;\n\treadonly reason?: string;\n\treadonly attributes: McpAttributes;\n}\n\nexport interface McpAuthorizationDenyDecision {\n\treadonly effect: \"deny\";\n\treadonly policy?: string;\n\treadonly reason: string;\n\treadonly attributes: McpAttributes;\n}\n\n/** Explicit authorization result. Missing or malformed results are never treated as allow. */\nexport type McpAuthorizationDecision = McpAuthorizationAllowDecision | McpAuthorizationDenyDecision;\n\n/** Framework-neutral policy evaluated against the complete operation envelope. */\nexport interface McpAuthorizationPolicy<\n\tInput = unknown,\n\tContext extends McpOperationContext = McpOperationContext,\n> {\n\tauthorize(operation: McpOperation<Input, Context>): MaybePromise<McpAuthorizationDecision>;\n}\n\nexport interface McpAuthorizationDecisionInit {\n\treadonly policy?: string;\n\treadonly reason?: string;\n\treadonly attributes?: McpAttributes;\n}\n\nexport type McpAuthorizationFailure =\n\t\"denied\" | \"missing-policy\" | \"invalid-decision\" | \"policy-error\";\n\n/** Fail-closed error raised before a denied operation reaches its terminal handler. */\nexport class McpAuthorizationError extends Error {\n\treadonly code = MCP_AUTHORIZATION_DENIED;\n\treadonly failure: McpAuthorizationFailure;\n\treadonly operationId: string;\n\treadonly decision: McpAuthorizationDenyDecision;\n\n\tconstructor(\n\t\toperation: McpOperation,\n\t\tdecision: McpAuthorizationDenyDecision,\n\t\tfailure: McpAuthorizationFailure,\n\t\toptions?: ErrorOptions,\n\t) {\n\t\tsuper(\"MCP operation authorization was denied.\", options);\n\t\tthis.name = \"McpAuthorizationError\";\n\t\tthis.failure = failure;\n\t\tthis.operationId = operation.context.operationId;\n\t\tthis.decision = decision;\n\t}\n}\n\n/** Constructs a frozen allow decision. */\nexport function allowMcpOperation(\n\tinit: McpAuthorizationDecisionInit = {},\n): McpAuthorizationAllowDecision {\n\tassertOptionalNonEmpty(init.policy, \"policy\");\n\tassertOptionalNonEmpty(init.reason, \"reason\");\n\treturn Object.freeze({\n\t\teffect: \"allow\",\n\t\t...(init.policy === undefined ? {} : { policy: init.policy }),\n\t\t...(init.reason === undefined ? {} : { reason: init.reason }),\n\t\tattributes: copyMcpAttributes(init.attributes),\n\t});\n}\n\n/** Constructs a frozen deny decision with a required, non-empty reason. */\nexport function denyMcpOperation(\n\treason: string,\n\tinit: Omit<McpAuthorizationDecisionInit, \"reason\"> = {},\n): McpAuthorizationDenyDecision {\n\tassertNonEmpty(reason, \"reason\");\n\tassertOptionalNonEmpty(init.policy, \"policy\");\n\treturn Object.freeze({\n\t\teffect: \"deny\",\n\t\t...(init.policy === undefined ? {} : { policy: init.policy }),\n\t\treason,\n\t\tattributes: copyMcpAttributes(init.attributes),\n\t});\n}\n\n/**\n * Evaluates a policy and returns only an explicit allow. A missing policy,\n * policy exception, malformed result, or deny decision raises\n * `McpAuthorizationError` and therefore fails closed.\n */\nexport async function enforceMcpAuthorization<\n\tInput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(\n\tpolicy: McpAuthorizationPolicy<Input, Context> | undefined,\n\toperation: McpOperation<Input, Context>,\n): Promise<McpAuthorizationAllowDecision> {\n\tif (policy === undefined) {\n\t\tthrow authorizationError(\n\t\t\toperation,\n\t\t\tdenyMcpOperation(\"No authorization policy is configured.\"),\n\t\t\t\"missing-policy\",\n\t\t);\n\t}\n\n\tlet decision: unknown;\n\ttry {\n\t\tdecision = await policy.authorize(operation);\n\t} catch (cause) {\n\t\tthrow authorizationError(\n\t\t\toperation,\n\t\t\tdenyMcpOperation(\"The authorization policy failed.\"),\n\t\t\t\"policy-error\",\n\t\t\t{ cause },\n\t\t);\n\t}\n\n\tlet normalizedDecision: McpAuthorizationDecision | undefined;\n\ttry {\n\t\tnormalizedDecision = normalizeAuthorizationDecision(decision);\n\t} catch (cause) {\n\t\tthrow authorizationError(\n\t\t\toperation,\n\t\t\tdenyMcpOperation(\"The authorization policy returned an invalid decision.\"),\n\t\t\t\"invalid-decision\",\n\t\t\t{ cause },\n\t\t);\n\t}\n\n\tif (normalizedDecision === undefined) {\n\t\tthrow authorizationError(\n\t\t\toperation,\n\t\t\tdenyMcpOperation(\"The authorization policy returned an invalid decision.\"),\n\t\t\t\"invalid-decision\",\n\t\t);\n\t}\n\n\tif (normalizedDecision.effect === \"deny\") {\n\t\tthrow authorizationError(operation, normalizedDecision, \"denied\");\n\t}\n\n\treturn normalizedDecision;\n}\n\n/** Creates middleware that enforces authorization before invoking the next stage. */\nexport function createMcpAuthorizationMiddleware<\n\tInput,\n\tOutput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(\n\tpolicy: McpAuthorizationPolicy<Input, Context> | undefined,\n): McpOperationMiddleware<Input, Output, Context> {\n\treturn async (operation, next) => {\n\t\tawait enforceMcpAuthorization(policy, operation);\n\t\treturn next();\n\t};\n}\n\nfunction normalizeAuthorizationDecision(value: unknown): McpAuthorizationDecision | undefined {\n\tif (typeof value !== \"object\" || value === null) return undefined;\n\tconst candidate = value as Partial<McpAuthorizationDecision>;\n\tif (candidate.effect !== \"allow\" && candidate.effect !== \"deny\") return undefined;\n\tif (!isAttributes(candidate.attributes)) return undefined;\n\tif (!isOptionalNonEmpty(candidate.policy)) return undefined;\n\tif (candidate.effect === \"deny\") {\n\t\tif (typeof candidate.reason !== \"string\" || candidate.reason.trim().length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn denyMcpOperation(candidate.reason, {\n\t\t\t...(candidate.policy === undefined ? {} : { policy: candidate.policy }),\n\t\t\tattributes: candidate.attributes,\n\t\t});\n\t}\n\tif (!isOptionalNonEmpty(candidate.reason)) return undefined;\n\treturn allowMcpOperation({\n\t\t...(candidate.policy === undefined ? {} : { policy: candidate.policy }),\n\t\t...(candidate.reason === undefined ? {} : { reason: candidate.reason }),\n\t\tattributes: candidate.attributes,\n\t});\n}\n\nfunction authorizationError<Input, Context extends McpOperationContext>(\n\toperation: McpOperation<Input, Context>,\n\tdecision: McpAuthorizationDenyDecision,\n\tfailure: McpAuthorizationFailure,\n\toptions?: ErrorOptions,\n): McpAuthorizationError {\n\treturn new McpAuthorizationError(operation, decision, failure, options);\n}\n\nfunction isAttributes(value: unknown): value is McpAttributes {\n\ttry {\n\t\tcopyMcpAttributes(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isOptionalNonEmpty(value: unknown): value is string | undefined {\n\treturn value === undefined || (typeof value === \"string\" && value.trim().length > 0);\n}\n\nfunction assertNonEmpty(value: string, field: string): void {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new TypeError(`${field} must be a non-empty string.`);\n\t}\n}\n\nfunction assertOptionalNonEmpty(value: string | undefined, field: string): void {\n\tif (value !== undefined) assertNonEmpty(value, field);\n}\n"],"mappings":"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"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { a as McpOperationHandler, c as McpOperationMiddleware, d as createMcpOperation, f as createMcpOperationContext, h as McpAttributes, i as McpOperationContextInit, l as McpOperationNext, m as McpAttributeValue, n as McpOperation, o as McpOperationKind, p as McpAttributeScalar, r as McpOperationContext, s as McpOperationMetadata, t as MaybePromise, u as McpRuntimeRole } from "./operation-D33Ttxve.mjs";
|
|
2
|
+
import { MCP_AUTHORIZATION_DENIED, McpAuthorizationAllowDecision, McpAuthorizationDecision, McpAuthorizationDecisionInit, McpAuthorizationDenyDecision, McpAuthorizationError, McpAuthorizationFailure, McpAuthorizationPolicy, allowMcpOperation, createMcpAuthorizationMiddleware, denyMcpOperation, enforceMcpAuthorization } from "./authorization.mjs";
|
|
3
|
+
import { McpErrorDetails, McpLifecycleEvent, McpLifecycleMiddlewareOptions, McpLifecycleObserver, McpOperationCancelledEvent, McpOperationFailedEvent, McpOperationStartedEvent, McpOperationSucceededEvent, composeMcpLifecycleObservers, createMcpLifecycleMiddleware, toMcpErrorDetails } from "./lifecycle.mjs";
|
|
4
|
+
import { MCP_MIDDLEWARE_REENTRY, McpMiddlewareReentryError, McpPassthroughMiddleware, composeMcpMiddleware, createMcpPassthroughMiddleware } from "./middleware.mjs";
|
|
5
|
+
export { MCP_AUTHORIZATION_DENIED, MCP_MIDDLEWARE_REENTRY, type MaybePromise, type McpAttributeScalar, type McpAttributeValue, type McpAttributes, type McpAuthorizationAllowDecision, type McpAuthorizationDecision, type McpAuthorizationDecisionInit, type McpAuthorizationDenyDecision, McpAuthorizationError, type McpAuthorizationFailure, type McpAuthorizationPolicy, type McpErrorDetails, type McpLifecycleEvent, type McpLifecycleMiddlewareOptions, type McpLifecycleObserver, McpMiddlewareReentryError, type McpOperation, type McpOperationCancelledEvent, type McpOperationContext, type McpOperationContextInit, type McpOperationFailedEvent, type McpOperationHandler, type McpOperationKind, type McpOperationMetadata, type McpOperationMiddleware, type McpOperationNext, type McpOperationStartedEvent, type McpOperationSucceededEvent, type McpPassthroughMiddleware, type McpRuntimeRole, allowMcpOperation, composeMcpLifecycleObservers, composeMcpMiddleware, createMcpAuthorizationMiddleware, createMcpLifecycleMiddleware, createMcpOperation, createMcpOperationContext, createMcpPassthroughMiddleware, denyMcpOperation, enforceMcpAuthorization, toMcpErrorDetails };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { MCP_AUTHORIZATION_DENIED, McpAuthorizationError, allowMcpOperation, createMcpAuthorizationMiddleware, denyMcpOperation, enforceMcpAuthorization } from "./authorization.mjs";
|
|
2
|
+
import { composeMcpLifecycleObservers, createMcpLifecycleMiddleware, toMcpErrorDetails } from "./lifecycle.mjs";
|
|
3
|
+
import { MCP_MIDDLEWARE_REENTRY, McpMiddlewareReentryError, composeMcpMiddleware, createMcpPassthroughMiddleware } from "./middleware.mjs";
|
|
4
|
+
import { createMcpOperation, createMcpOperationContext } from "./operation.mjs";
|
|
5
|
+
export { MCP_AUTHORIZATION_DENIED, MCP_MIDDLEWARE_REENTRY, McpAuthorizationError, McpMiddlewareReentryError, allowMcpOperation, composeMcpLifecycleObservers, composeMcpMiddleware, createMcpAuthorizationMiddleware, createMcpLifecycleMiddleware, createMcpOperation, createMcpOperationContext, createMcpPassthroughMiddleware, denyMcpOperation, enforceMcpAuthorization, toMcpErrorDetails };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { c as McpOperationMiddleware, r as McpOperationContext, t as MaybePromise } from "./operation-D33Ttxve.mjs";
|
|
2
|
+
//#region src/lifecycle.d.ts
|
|
3
|
+
interface McpErrorDetails {
|
|
4
|
+
readonly name: string;
|
|
5
|
+
readonly message: string;
|
|
6
|
+
readonly code?: string;
|
|
7
|
+
}
|
|
8
|
+
interface McpLifecycleEventBase<Context extends McpOperationContext> {
|
|
9
|
+
readonly timestamp: number;
|
|
10
|
+
readonly context: Context;
|
|
11
|
+
}
|
|
12
|
+
interface McpOperationStartedEvent<Context extends McpOperationContext = McpOperationContext> extends McpLifecycleEventBase<Context> {
|
|
13
|
+
readonly type: "operation.started";
|
|
14
|
+
}
|
|
15
|
+
interface McpOperationSucceededEvent<Context extends McpOperationContext = McpOperationContext> extends McpLifecycleEventBase<Context> {
|
|
16
|
+
readonly type: "operation.succeeded";
|
|
17
|
+
readonly durationMs: number;
|
|
18
|
+
}
|
|
19
|
+
interface McpOperationFailedEvent<Context extends McpOperationContext = McpOperationContext> extends McpLifecycleEventBase<Context> {
|
|
20
|
+
readonly type: "operation.failed";
|
|
21
|
+
readonly durationMs: number;
|
|
22
|
+
readonly error: McpErrorDetails;
|
|
23
|
+
}
|
|
24
|
+
interface McpOperationCancelledEvent<Context extends McpOperationContext = McpOperationContext> extends McpLifecycleEventBase<Context> {
|
|
25
|
+
readonly type: "operation.cancelled";
|
|
26
|
+
readonly durationMs: number;
|
|
27
|
+
readonly error: McpErrorDetails;
|
|
28
|
+
}
|
|
29
|
+
/** Lifecycle events intentionally omit operation inputs and outputs to avoid payload leakage. */
|
|
30
|
+
type McpLifecycleEvent<Context extends McpOperationContext = McpOperationContext> = McpOperationStartedEvent<Context> | McpOperationSucceededEvent<Context> | McpOperationFailedEvent<Context> | McpOperationCancelledEvent<Context>;
|
|
31
|
+
/** Destination for structured runtime lifecycle events. */
|
|
32
|
+
interface McpLifecycleObserver<Context extends McpOperationContext = McpOperationContext> {
|
|
33
|
+
onEvent(event: McpLifecycleEvent<Context>): MaybePromise<void>;
|
|
34
|
+
}
|
|
35
|
+
interface McpLifecycleMiddlewareOptions<Context extends McpOperationContext = McpOperationContext> {
|
|
36
|
+
/** Unix epoch milliseconds. Injectable for deterministic tests and alternate clocks. */
|
|
37
|
+
readonly now?: () => number;
|
|
38
|
+
/** Observer failures never replace an operation result or error. */
|
|
39
|
+
readonly onObserverError?: (error: unknown, event: McpLifecycleEvent<Context>) => MaybePromise<void>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Fans out to a snapshot of observers. Every observer is attempted; once all
|
|
43
|
+
* settle, one failure is rethrown directly and multiple failures as an
|
|
44
|
+
* `AggregateError`.
|
|
45
|
+
*/
|
|
46
|
+
declare function composeMcpLifecycleObservers<Context extends McpOperationContext = McpOperationContext>(observers: readonly McpLifecycleObserver<Context>[]): McpLifecycleObserver<Context>;
|
|
47
|
+
/**
|
|
48
|
+
* Creates best-effort lifecycle instrumentation. Observer failures are reported
|
|
49
|
+
* through `onObserverError` and never change the operation's result or primary
|
|
50
|
+
* error. A rejected operation is classified as cancelled when its signal is
|
|
51
|
+
* aborted at the point of rejection.
|
|
52
|
+
*/
|
|
53
|
+
declare function createMcpLifecycleMiddleware<Input, Output, Context extends McpOperationContext = McpOperationContext>(observer: McpLifecycleObserver<Context>, options?: McpLifecycleMiddlewareOptions<Context>): McpOperationMiddleware<Input, Output, Context>;
|
|
54
|
+
/** Converts an unknown throwable into a small, serializable telemetry shape. */
|
|
55
|
+
declare function toMcpErrorDetails(error: unknown): McpErrorDetails;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { McpErrorDetails, McpLifecycleEvent, McpLifecycleMiddlewareOptions, McpLifecycleObserver, McpOperationCancelledEvent, McpOperationFailedEvent, McpOperationStartedEvent, McpOperationSucceededEvent, composeMcpLifecycleObservers, createMcpLifecycleMiddleware, toMcpErrorDetails };
|
|
58
|
+
//# sourceMappingURL=lifecycle.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lifecycle.d.mts","names":[],"sources":["../src/lifecycle.ts"],"mappings":";;UAEiB;WACP;WACA;WACA;;UAGA,sBAAsB,gBAAgB;WACtC;WACA,SAAS;;UAGF,yBAChB,gBAAgB,sBAAsB,6BAC7B,sBAAsB;WACtB;;UAGO,2BAChB,gBAAgB,sBAAsB,6BAC7B,sBAAsB;WACtB;WACA;;UAGO,wBAChB,gBAAgB,sBAAsB,6BAC7B,sBAAsB;WACtB;WACA;WACA,OAAO;;UAGA,2BAChB,gBAAgB,sBAAsB,6BAC7B,sBAAsB;WACtB;WACA;WACA,OAAO;;;KAIL,kBAAkB,gBAAgB,sBAAsB,uBACjE,yBAAyB,WACzB,2BAA2B,WAC3B,wBAAwB,WACxB,2BAA2B;;UAGb,qBAAqB,gBAAgB,sBAAsB;EAC3E,QAAQ,OAAO,kBAAkB,WAAW;;UAG5B,8BAChB,gBAAgB,sBAAsB;;WAG7B;;WAEA,mBACR,gBACA,OAAO,kBAAkB,aACrB;;;;;;;iBAQU,6BACf,gBAAgB,sBAAsB,qBACrC,oBAAoB,qBAAqB,aAAa,qBAAqB;;;;;;;iBA+B7D,6BACf,OACA,QACA,gBAAgB,sBAAsB,qBAEtC,UAAU,qBAAqB,UAC/B,UAAS,8BAA8B,WACrC,uBAAuB,OAAO,QAAQ;;iBAkDzB,kBAAkB,iBAAiB"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
//#region src/lifecycle.ts
|
|
2
|
+
/**
|
|
3
|
+
* Fans out to a snapshot of observers. Every observer is attempted; once all
|
|
4
|
+
* settle, one failure is rethrown directly and multiple failures as an
|
|
5
|
+
* `AggregateError`.
|
|
6
|
+
*/
|
|
7
|
+
function composeMcpLifecycleObservers(observers) {
|
|
8
|
+
const snapshot = observers.map((observer, index) => {
|
|
9
|
+
if (typeof observer?.onEvent !== "function") throw new TypeError(`observers[${String(index)}].onEvent must be a function.`);
|
|
10
|
+
return observer;
|
|
11
|
+
});
|
|
12
|
+
return Object.freeze({ async onEvent(event) {
|
|
13
|
+
const failures = (await Promise.allSettled(snapshot.map(async (observer) => observer.onEvent(event)))).filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
14
|
+
if (failures.length === 1) throw failures[0];
|
|
15
|
+
if (failures.length > 1) throw new AggregateError(failures, "Multiple MCP lifecycle observers failed.");
|
|
16
|
+
} });
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Creates best-effort lifecycle instrumentation. Observer failures are reported
|
|
20
|
+
* through `onObserverError` and never change the operation's result or primary
|
|
21
|
+
* error. A rejected operation is classified as cancelled when its signal is
|
|
22
|
+
* aborted at the point of rejection.
|
|
23
|
+
*/
|
|
24
|
+
function createMcpLifecycleMiddleware(observer, options = {}) {
|
|
25
|
+
if (typeof observer?.onEvent !== "function") throw new TypeError("observer.onEvent must be a function.");
|
|
26
|
+
const now = options.now ?? Date.now;
|
|
27
|
+
return async (operation, next) => {
|
|
28
|
+
const startedAt = readTimestamp(now);
|
|
29
|
+
await emitSafely(observer, Object.freeze({
|
|
30
|
+
type: "operation.started",
|
|
31
|
+
timestamp: startedAt,
|
|
32
|
+
context: operation.context
|
|
33
|
+
}), options.onObserverError);
|
|
34
|
+
try {
|
|
35
|
+
const output = await next();
|
|
36
|
+
const finishedAt = readTimestamp(now);
|
|
37
|
+
await emitSafely(observer, Object.freeze({
|
|
38
|
+
type: "operation.succeeded",
|
|
39
|
+
timestamp: finishedAt,
|
|
40
|
+
durationMs: duration(startedAt, finishedAt),
|
|
41
|
+
context: operation.context
|
|
42
|
+
}), options.onObserverError);
|
|
43
|
+
return output;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
const finishedAt = readTimestamp(now);
|
|
46
|
+
await emitSafely(observer, Object.freeze({
|
|
47
|
+
type: operation.context.signal.aborted ? "operation.cancelled" : "operation.failed",
|
|
48
|
+
timestamp: finishedAt,
|
|
49
|
+
durationMs: duration(startedAt, finishedAt),
|
|
50
|
+
context: operation.context,
|
|
51
|
+
error: toMcpErrorDetails(error)
|
|
52
|
+
}), options.onObserverError);
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Converts an unknown throwable into a small, serializable telemetry shape. */
|
|
58
|
+
function toMcpErrorDetails(error) {
|
|
59
|
+
if (error instanceof Error) return Object.freeze({
|
|
60
|
+
name: error.name || "Error",
|
|
61
|
+
message: error.message,
|
|
62
|
+
...readErrorCode(error)
|
|
63
|
+
});
|
|
64
|
+
if (typeof error === "string") return Object.freeze({
|
|
65
|
+
name: "Error",
|
|
66
|
+
message: error
|
|
67
|
+
});
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
name: "UnknownError",
|
|
70
|
+
message: safeString(error),
|
|
71
|
+
...readErrorCode(error)
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
async function emitSafely(observer, event, onObserverError) {
|
|
75
|
+
try {
|
|
76
|
+
await observer.onEvent(event);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (onObserverError === void 0) return;
|
|
79
|
+
try {
|
|
80
|
+
await onObserverError(error, event);
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function readTimestamp(now) {
|
|
85
|
+
try {
|
|
86
|
+
const timestamp = now();
|
|
87
|
+
if (Number.isFinite(timestamp)) return timestamp;
|
|
88
|
+
} catch {}
|
|
89
|
+
try {
|
|
90
|
+
const fallback = Date.now();
|
|
91
|
+
if (Number.isFinite(fallback)) return fallback;
|
|
92
|
+
} catch {}
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
function duration(startedAt, finishedAt) {
|
|
96
|
+
return Math.max(0, finishedAt - startedAt);
|
|
97
|
+
}
|
|
98
|
+
function readErrorCode(error) {
|
|
99
|
+
if (typeof error !== "object" || error === null) return {};
|
|
100
|
+
try {
|
|
101
|
+
const code = error.code;
|
|
102
|
+
if (typeof code === "string" || typeof code === "number") return { code: String(code) };
|
|
103
|
+
} catch {}
|
|
104
|
+
return {};
|
|
105
|
+
}
|
|
106
|
+
function safeString(value) {
|
|
107
|
+
try {
|
|
108
|
+
return String(value);
|
|
109
|
+
} catch {
|
|
110
|
+
return "Unknown thrown value";
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
export { composeMcpLifecycleObservers, createMcpLifecycleMiddleware, toMcpErrorDetails };
|
|
115
|
+
|
|
116
|
+
//# sourceMappingURL=lifecycle.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lifecycle.mjs","names":[],"sources":["../src/lifecycle.ts"],"sourcesContent":["import type { McpOperationContext, McpOperationMiddleware, MaybePromise } from \"./operation.ts\";\n\nexport interface McpErrorDetails {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly code?: string;\n}\n\ninterface McpLifecycleEventBase<Context extends McpOperationContext> {\n\treadonly timestamp: number;\n\treadonly context: Context;\n}\n\nexport interface McpOperationStartedEvent<\n\tContext extends McpOperationContext = McpOperationContext,\n> extends McpLifecycleEventBase<Context> {\n\treadonly type: \"operation.started\";\n}\n\nexport interface McpOperationSucceededEvent<\n\tContext extends McpOperationContext = McpOperationContext,\n> extends McpLifecycleEventBase<Context> {\n\treadonly type: \"operation.succeeded\";\n\treadonly durationMs: number;\n}\n\nexport interface McpOperationFailedEvent<\n\tContext extends McpOperationContext = McpOperationContext,\n> extends McpLifecycleEventBase<Context> {\n\treadonly type: \"operation.failed\";\n\treadonly durationMs: number;\n\treadonly error: McpErrorDetails;\n}\n\nexport interface McpOperationCancelledEvent<\n\tContext extends McpOperationContext = McpOperationContext,\n> extends McpLifecycleEventBase<Context> {\n\treadonly type: \"operation.cancelled\";\n\treadonly durationMs: number;\n\treadonly error: McpErrorDetails;\n}\n\n/** Lifecycle events intentionally omit operation inputs and outputs to avoid payload leakage. */\nexport type McpLifecycleEvent<Context extends McpOperationContext = McpOperationContext> =\n\t| McpOperationStartedEvent<Context>\n\t| McpOperationSucceededEvent<Context>\n\t| McpOperationFailedEvent<Context>\n\t| McpOperationCancelledEvent<Context>;\n\n/** Destination for structured runtime lifecycle events. */\nexport interface McpLifecycleObserver<Context extends McpOperationContext = McpOperationContext> {\n\tonEvent(event: McpLifecycleEvent<Context>): MaybePromise<void>;\n}\n\nexport interface McpLifecycleMiddlewareOptions<\n\tContext extends McpOperationContext = McpOperationContext,\n> {\n\t/** Unix epoch milliseconds. Injectable for deterministic tests and alternate clocks. */\n\treadonly now?: () => number;\n\t/** Observer failures never replace an operation result or error. */\n\treadonly onObserverError?: (\n\t\terror: unknown,\n\t\tevent: McpLifecycleEvent<Context>,\n\t) => MaybePromise<void>;\n}\n\n/**\n * Fans out to a snapshot of observers. Every observer is attempted; once all\n * settle, one failure is rethrown directly and multiple failures as an\n * `AggregateError`.\n */\nexport function composeMcpLifecycleObservers<\n\tContext extends McpOperationContext = McpOperationContext,\n>(observers: readonly McpLifecycleObserver<Context>[]): McpLifecycleObserver<Context> {\n\tconst snapshot = observers.map((observer, index) => {\n\t\tif (typeof observer?.onEvent !== \"function\") {\n\t\t\tthrow new TypeError(`observers[${String(index)}].onEvent must be a function.`);\n\t\t}\n\t\treturn observer;\n\t});\n\n\treturn Object.freeze({\n\t\tasync onEvent(event: McpLifecycleEvent<Context>): Promise<void> {\n\t\t\tconst settled = await Promise.allSettled(\n\t\t\t\tsnapshot.map(async (observer) => observer.onEvent(event)),\n\t\t\t);\n\t\t\tconst failures = settled\n\t\t\t\t.filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n\t\t\t\t.map((result) => result.reason as unknown);\n\n\t\t\tif (failures.length === 1) throw failures[0];\n\t\t\tif (failures.length > 1) {\n\t\t\t\tthrow new AggregateError(failures, \"Multiple MCP lifecycle observers failed.\");\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * Creates best-effort lifecycle instrumentation. Observer failures are reported\n * through `onObserverError` and never change the operation's result or primary\n * error. A rejected operation is classified as cancelled when its signal is\n * aborted at the point of rejection.\n */\nexport function createMcpLifecycleMiddleware<\n\tInput,\n\tOutput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(\n\tobserver: McpLifecycleObserver<Context>,\n\toptions: McpLifecycleMiddlewareOptions<Context> = {},\n): McpOperationMiddleware<Input, Output, Context> {\n\tif (typeof observer?.onEvent !== \"function\") {\n\t\tthrow new TypeError(\"observer.onEvent must be a function.\");\n\t}\n\tconst now = options.now ?? Date.now;\n\n\treturn async (operation, next) => {\n\t\tconst startedAt = readTimestamp(now);\n\t\tawait emitSafely(\n\t\t\tobserver,\n\t\t\tObject.freeze({\n\t\t\t\ttype: \"operation.started\",\n\t\t\t\ttimestamp: startedAt,\n\t\t\t\tcontext: operation.context,\n\t\t\t}),\n\t\t\toptions.onObserverError,\n\t\t);\n\n\t\ttry {\n\t\t\tconst output = await next();\n\t\t\tconst finishedAt = readTimestamp(now);\n\t\t\tawait emitSafely(\n\t\t\t\tobserver,\n\t\t\t\tObject.freeze({\n\t\t\t\t\ttype: \"operation.succeeded\",\n\t\t\t\t\ttimestamp: finishedAt,\n\t\t\t\t\tdurationMs: duration(startedAt, finishedAt),\n\t\t\t\t\tcontext: operation.context,\n\t\t\t\t}),\n\t\t\t\toptions.onObserverError,\n\t\t\t);\n\t\t\treturn output;\n\t\t} catch (error) {\n\t\t\tconst finishedAt = readTimestamp(now);\n\t\t\tconst event = Object.freeze({\n\t\t\t\ttype: operation.context.signal.aborted\n\t\t\t\t\t? (\"operation.cancelled\" as const)\n\t\t\t\t\t: (\"operation.failed\" as const),\n\t\t\t\ttimestamp: finishedAt,\n\t\t\t\tdurationMs: duration(startedAt, finishedAt),\n\t\t\t\tcontext: operation.context,\n\t\t\t\terror: toMcpErrorDetails(error),\n\t\t\t}) satisfies McpOperationCancelledEvent<Context> | McpOperationFailedEvent<Context>;\n\t\t\tawait emitSafely(observer, event, options.onObserverError);\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n\n/** Converts an unknown throwable into a small, serializable telemetry shape. */\nexport function toMcpErrorDetails(error: unknown): McpErrorDetails {\n\tif (error instanceof Error) {\n\t\treturn Object.freeze({\n\t\t\tname: error.name || \"Error\",\n\t\t\tmessage: error.message,\n\t\t\t...readErrorCode(error),\n\t\t});\n\t}\n\n\tif (typeof error === \"string\") {\n\t\treturn Object.freeze({ name: \"Error\", message: error });\n\t}\n\n\treturn Object.freeze({\n\t\tname: \"UnknownError\",\n\t\tmessage: safeString(error),\n\t\t...readErrorCode(error),\n\t});\n}\n\nasync function emitSafely<Context extends McpOperationContext>(\n\tobserver: McpLifecycleObserver<Context>,\n\tevent: McpLifecycleEvent<Context>,\n\tonObserverError:\n\t\t((error: unknown, event: McpLifecycleEvent<Context>) => MaybePromise<void>) | undefined,\n): Promise<void> {\n\ttry {\n\t\tawait observer.onEvent(event);\n\t} catch (error) {\n\t\tif (onObserverError === undefined) return;\n\t\ttry {\n\t\t\tawait onObserverError(error, event);\n\t\t} catch {\n\t\t\t// Observability must not replace the operation result or its primary error.\n\t\t}\n\t}\n}\n\nfunction readTimestamp(now: () => number): number {\n\ttry {\n\t\tconst timestamp = now();\n\t\tif (Number.isFinite(timestamp)) return timestamp;\n\t} catch {\n\t\t// A telemetry clock is instrumentation and must not alter the operation.\n\t}\n\ttry {\n\t\tconst fallback = Date.now();\n\t\tif (Number.isFinite(fallback)) return fallback;\n\t} catch {\n\t\t// Extremely defensive fallback for a hostile or patched global clock.\n\t}\n\treturn 0;\n}\n\nfunction duration(startedAt: number, finishedAt: number): number {\n\treturn Math.max(0, finishedAt - startedAt);\n}\n\nfunction readErrorCode(error: unknown): { readonly code?: string } {\n\tif (typeof error !== \"object\" || error === null) return {};\n\ttry {\n\t\tconst code = (error as { readonly code?: unknown }).code;\n\t\tif (typeof code === \"string\" || typeof code === \"number\") {\n\t\t\treturn { code: String(code) };\n\t\t}\n\t} catch {\n\t\t// A hostile getter should not make telemetry serialization fail.\n\t}\n\treturn {};\n}\n\nfunction safeString(value: unknown): string {\n\ttry {\n\t\treturn String(value);\n\t} catch {\n\t\treturn \"Unknown thrown value\";\n\t}\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { a as McpOperationHandler, c as McpOperationMiddleware, l as McpOperationNext, n as McpOperation, r as McpOperationContext, t as MaybePromise } from "./operation-D33Ttxve.mjs";
|
|
2
|
+
//#region src/middleware.d.ts
|
|
3
|
+
declare const MCP_MIDDLEWARE_REENTRY: "MCP_MIDDLEWARE_REENTRY";
|
|
4
|
+
/** Raised when middleware invokes its continuation more than once. */
|
|
5
|
+
declare class McpMiddlewareReentryError extends Error {
|
|
6
|
+
readonly code: "MCP_MIDDLEWARE_REENTRY";
|
|
7
|
+
readonly middlewareIndex: number;
|
|
8
|
+
constructor(middlewareIndex: number);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Result-opaque middleware for logging, tracing, rate limits, and other
|
|
12
|
+
* concerns that must not replace a protocol result.
|
|
13
|
+
*
|
|
14
|
+
* The continuation deliberately resolves to `void`. The adapter retains the
|
|
15
|
+
* downstream value and returns that exact value after the middleware settles.
|
|
16
|
+
*/
|
|
17
|
+
type McpPassthroughMiddleware<Input = unknown, Context extends McpOperationContext = McpOperationContext> = (operation: McpOperation<Input, Context>, next: McpOperationNext<void>) => MaybePromise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Adapts result-opaque middleware to the regular transforming middleware
|
|
20
|
+
* contract while guaranteeing that successful downstream results and errors
|
|
21
|
+
* cannot be silently substituted or swallowed.
|
|
22
|
+
*/
|
|
23
|
+
declare function createMcpPassthroughMiddleware<Input, Output, Context extends McpOperationContext = McpOperationContext>(middleware: McpPassthroughMiddleware<Input, Context>): McpOperationMiddleware<Input, Output, Context>;
|
|
24
|
+
/**
|
|
25
|
+
* Composes middleware around a terminal handler. The input list is snapshotted
|
|
26
|
+
* and each invocation gets an independent re-entry guard, so a reused pipeline
|
|
27
|
+
* remains safe under concurrency.
|
|
28
|
+
*/
|
|
29
|
+
declare function composeMcpMiddleware<Input, Output, Context extends McpOperationContext = McpOperationContext>(middleware: readonly McpOperationMiddleware<Input, Output, Context>[], terminal: McpOperationHandler<Input, Output, Context>): (operation: Parameters<McpOperationHandler<Input, Output, Context>>[0]) => Promise<Output>;
|
|
30
|
+
//#endregion
|
|
31
|
+
export { MCP_MIDDLEWARE_REENTRY, McpMiddlewareReentryError, McpPassthroughMiddleware, composeMcpMiddleware, createMcpPassthroughMiddleware };
|
|
32
|
+
//# sourceMappingURL=middleware.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.d.mts","names":[],"sources":["../src/middleware.ts"],"mappings":";;cASa;;cAGA,kCAAkC;WACrC;WACA;EAET,YAAY;;;;;;;;;KAcD,yBACX,iBACA,gBAAgB,sBAAsB,wBAClC,WAAW,aAAa,OAAO,UAAU,MAAM,2BAA2B;;;;;;iBAO/D,+BACf,OACA,QACA,gBAAgB,sBAAsB,qBAEtC,YAAY,yBAAyB,OAAO,WAC1C,uBAAuB,OAAO,QAAQ;;;;;;iBA0BzB,qBACf,OACA,QACA,gBAAgB,sBAAsB,qBAEtC,qBAAqB,uBAAuB,OAAO,QAAQ,YAC3D,UAAU,oBAAoB,OAAO,QAAQ,YAC1C,WAAW,WAAW,oBAAoB,OAAO,QAAQ,iBAAiB,QAAQ"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//#region src/middleware.ts
|
|
2
|
+
const MCP_MIDDLEWARE_REENTRY = "MCP_MIDDLEWARE_REENTRY";
|
|
3
|
+
/** Raised when middleware invokes its continuation more than once. */
|
|
4
|
+
var McpMiddlewareReentryError = class extends Error {
|
|
5
|
+
code = MCP_MIDDLEWARE_REENTRY;
|
|
6
|
+
middlewareIndex;
|
|
7
|
+
constructor(middlewareIndex) {
|
|
8
|
+
super(`MCP middleware at index ${String(middlewareIndex)} called next() more than once.`);
|
|
9
|
+
this.name = "McpMiddlewareReentryError";
|
|
10
|
+
this.middlewareIndex = middlewareIndex;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Adapts result-opaque middleware to the regular transforming middleware
|
|
15
|
+
* contract while guaranteeing that successful downstream results and errors
|
|
16
|
+
* cannot be silently substituted or swallowed.
|
|
17
|
+
*/
|
|
18
|
+
function createMcpPassthroughMiddleware(middleware) {
|
|
19
|
+
if (typeof middleware !== "function") throw new TypeError("passthrough middleware must be a function.");
|
|
20
|
+
return async (operation, next) => {
|
|
21
|
+
const continuation = {};
|
|
22
|
+
await middleware(operation, async () => {
|
|
23
|
+
const task = next();
|
|
24
|
+
continuation.task = task;
|
|
25
|
+
await task;
|
|
26
|
+
});
|
|
27
|
+
const task = continuation.task;
|
|
28
|
+
if (task === void 0) throw new TypeError("Passthrough MCP middleware must call next().");
|
|
29
|
+
return task;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Composes middleware around a terminal handler. The input list is snapshotted
|
|
34
|
+
* and each invocation gets an independent re-entry guard, so a reused pipeline
|
|
35
|
+
* remains safe under concurrency.
|
|
36
|
+
*/
|
|
37
|
+
function composeMcpMiddleware(middleware, terminal) {
|
|
38
|
+
if (typeof terminal !== "function") throw new TypeError("terminal must be a function.");
|
|
39
|
+
const chain = middleware.map((entry, index) => {
|
|
40
|
+
if (typeof entry !== "function") throw new TypeError(`middleware[${String(index)}] must be a function.`);
|
|
41
|
+
return entry;
|
|
42
|
+
});
|
|
43
|
+
return async (operation) => {
|
|
44
|
+
let highestDispatchedIndex = -1;
|
|
45
|
+
const dispatch = async (index) => {
|
|
46
|
+
if (index <= highestDispatchedIndex) throw new McpMiddlewareReentryError(Math.max(0, index - 1));
|
|
47
|
+
highestDispatchedIndex = index;
|
|
48
|
+
const current = chain[index];
|
|
49
|
+
if (current === void 0) return terminal(operation);
|
|
50
|
+
return current(operation, () => dispatch(index + 1));
|
|
51
|
+
};
|
|
52
|
+
return dispatch(0);
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
export { MCP_MIDDLEWARE_REENTRY, McpMiddlewareReentryError, composeMcpMiddleware, createMcpPassthroughMiddleware };
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["import type {\n\tMaybePromise,\n\tMcpOperation,\n\tMcpOperationContext,\n\tMcpOperationHandler,\n\tMcpOperationMiddleware,\n\tMcpOperationNext,\n} from \"./operation.ts\";\n\nexport const MCP_MIDDLEWARE_REENTRY = \"MCP_MIDDLEWARE_REENTRY\" as const;\n\n/** Raised when middleware invokes its continuation more than once. */\nexport class McpMiddlewareReentryError extends Error {\n\treadonly code = MCP_MIDDLEWARE_REENTRY;\n\treadonly middlewareIndex: number;\n\n\tconstructor(middlewareIndex: number) {\n\t\tsuper(`MCP middleware at index ${String(middlewareIndex)} called next() more than once.`);\n\t\tthis.name = \"McpMiddlewareReentryError\";\n\t\tthis.middlewareIndex = middlewareIndex;\n\t}\n}\n\n/**\n * Result-opaque middleware for logging, tracing, rate limits, and other\n * concerns that must not replace a protocol result.\n *\n * The continuation deliberately resolves to `void`. The adapter retains the\n * downstream value and returns that exact value after the middleware settles.\n */\nexport type McpPassthroughMiddleware<\n\tInput = unknown,\n\tContext extends McpOperationContext = McpOperationContext,\n> = (operation: McpOperation<Input, Context>, next: McpOperationNext<void>) => MaybePromise<void>;\n\n/**\n * Adapts result-opaque middleware to the regular transforming middleware\n * contract while guaranteeing that successful downstream results and errors\n * cannot be silently substituted or swallowed.\n */\nexport function createMcpPassthroughMiddleware<\n\tInput,\n\tOutput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(\n\tmiddleware: McpPassthroughMiddleware<Input, Context>,\n): McpOperationMiddleware<Input, Output, Context> {\n\tif (typeof middleware !== \"function\") {\n\t\tthrow new TypeError(\"passthrough middleware must be a function.\");\n\t}\n\n\treturn async (operation, next) => {\n\t\tconst continuation: { task?: Promise<Output> } = {};\n\t\tawait middleware(operation, async () => {\n\t\t\tconst task = next();\n\t\t\tcontinuation.task = task;\n\t\t\tawait task;\n\t\t});\n\n\t\tconst task = continuation.task;\n\t\tif (task === undefined) {\n\t\t\tthrow new TypeError(\"Passthrough MCP middleware must call next().\");\n\t\t}\n\t\treturn task;\n\t};\n}\n\n/**\n * Composes middleware around a terminal handler. The input list is snapshotted\n * and each invocation gets an independent re-entry guard, so a reused pipeline\n * remains safe under concurrency.\n */\nexport function composeMcpMiddleware<\n\tInput,\n\tOutput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(\n\tmiddleware: readonly McpOperationMiddleware<Input, Output, Context>[],\n\tterminal: McpOperationHandler<Input, Output, Context>,\n): (operation: Parameters<McpOperationHandler<Input, Output, Context>>[0]) => Promise<Output> {\n\tif (typeof terminal !== \"function\") {\n\t\tthrow new TypeError(\"terminal must be a function.\");\n\t}\n\n\tconst chain = middleware.map((entry, index) => {\n\t\tif (typeof entry !== \"function\") {\n\t\t\tthrow new TypeError(`middleware[${String(index)}] must be a function.`);\n\t\t}\n\t\treturn entry;\n\t});\n\n\treturn async (operation) => {\n\t\tlet highestDispatchedIndex = -1;\n\n\t\tconst dispatch = async (index: number): Promise<Output> => {\n\t\t\tif (index <= highestDispatchedIndex) {\n\t\t\t\tthrow new McpMiddlewareReentryError(Math.max(0, index - 1));\n\t\t\t}\n\t\t\thighestDispatchedIndex = index;\n\n\t\t\tconst current = chain[index];\n\t\t\tif (current === undefined) return terminal(operation);\n\t\t\treturn current(operation, () => dispatch(index + 1));\n\t\t};\n\n\t\treturn dispatch(0);\n\t};\n}\n"],"mappings":";AASA,MAAa,yBAAyB;;AAGtC,IAAa,4BAAb,cAA+C,MAAM;CACpD,OAAgB;CAChB;CAEA,YAAY,iBAAyB;EACpC,MAAM,2BAA2B,OAAO,eAAe,EAAE,+BAA+B;EACxF,KAAK,OAAO;EACZ,KAAK,kBAAkB;CACxB;AACD;;;;;;AAmBA,SAAgB,+BAKf,YACiD;CACjD,IAAI,OAAO,eAAe,YACzB,MAAM,IAAI,UAAU,4CAA4C;CAGjE,OAAO,OAAO,WAAW,SAAS;EACjC,MAAM,eAA2C,CAAC;EAClD,MAAM,WAAW,WAAW,YAAY;GACvC,MAAM,OAAO,KAAK;GAClB,aAAa,OAAO;GACpB,MAAM;EACP,CAAC;EAED,MAAM,OAAO,aAAa;EAC1B,IAAI,SAAS,KAAA,GACZ,MAAM,IAAI,UAAU,8CAA8C;EAEnE,OAAO;CACR;AACD;;;;;;AAOA,SAAgB,qBAKf,YACA,UAC6F;CAC7F,IAAI,OAAO,aAAa,YACvB,MAAM,IAAI,UAAU,8BAA8B;CAGnD,MAAM,QAAQ,WAAW,KAAK,OAAO,UAAU;EAC9C,IAAI,OAAO,UAAU,YACpB,MAAM,IAAI,UAAU,cAAc,OAAO,KAAK,EAAE,sBAAsB;EAEvE,OAAO;CACR,CAAC;CAED,OAAO,OAAO,cAAc;EAC3B,IAAI,yBAAyB;EAE7B,MAAM,WAAW,OAAO,UAAmC;GAC1D,IAAI,SAAS,wBACZ,MAAM,IAAI,0BAA0B,KAAK,IAAI,GAAG,QAAQ,CAAC,CAAC;GAE3D,yBAAyB;GAEzB,MAAM,UAAU,MAAM;GACtB,IAAI,YAAY,KAAA,GAAW,OAAO,SAAS,SAAS;GACpD,OAAO,QAAQ,iBAAiB,SAAS,QAAQ,CAAC,CAAC;EACpD;EAEA,OAAO,SAAS,CAAC;CAClB;AACD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
//#region src/attribute-values.d.ts
|
|
2
|
+
type McpAttributeScalar = string | number | boolean;
|
|
3
|
+
/** Immutable, telemetry-compatible operation dimension. */
|
|
4
|
+
type McpAttributeValue = McpAttributeScalar | readonly McpAttributeScalar[];
|
|
5
|
+
/** Low-cardinality dimensions safe to attach to operation and telemetry context. */
|
|
6
|
+
type McpAttributes = Readonly<Record<string, McpAttributeValue>>;
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/operation.d.ts
|
|
9
|
+
/** A value that may be produced synchronously or asynchronously. */
|
|
10
|
+
type MaybePromise<Value> = Value | PromiseLike<Value>;
|
|
11
|
+
/** The position at which an operation is running. */
|
|
12
|
+
type McpRuntimeRole = "client" | "server" | "gateway";
|
|
13
|
+
/** The protocol interaction represented by an operation. */
|
|
14
|
+
type McpOperationKind = "request" | "notification";
|
|
15
|
+
/** Stable metadata describing an operation independently of its input payload. */
|
|
16
|
+
interface McpOperationMetadata {
|
|
17
|
+
/** Protocol method or application-defined operation name. */
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly kind: McpOperationKind;
|
|
20
|
+
/** Optional capability family, such as `tools`, `resources`, or `prompts`. */
|
|
21
|
+
readonly capability?: string;
|
|
22
|
+
/** Optional logical target, such as an upstream server identifier. */
|
|
23
|
+
readonly target?: string;
|
|
24
|
+
readonly attributes: McpAttributes;
|
|
25
|
+
}
|
|
26
|
+
/** Immutable context propagated through one runtime operation. */
|
|
27
|
+
interface McpOperationContext<Principal = unknown> {
|
|
28
|
+
/** Runtime-unique identifier used to correlate logs and telemetry. */
|
|
29
|
+
readonly operationId: string;
|
|
30
|
+
readonly role: McpRuntimeRole;
|
|
31
|
+
readonly operation: McpOperationMetadata;
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
readonly requestId?: string;
|
|
34
|
+
readonly sessionId?: string;
|
|
35
|
+
readonly principal?: Principal;
|
|
36
|
+
readonly attributes: McpAttributes;
|
|
37
|
+
}
|
|
38
|
+
/** Input used to construct an immutable operation context. */
|
|
39
|
+
interface McpOperationContextInit<Principal = unknown> {
|
|
40
|
+
readonly operationId: string;
|
|
41
|
+
readonly role: McpRuntimeRole;
|
|
42
|
+
readonly operation: Omit<McpOperationMetadata, "attributes"> & {
|
|
43
|
+
readonly attributes?: McpAttributes;
|
|
44
|
+
};
|
|
45
|
+
readonly signal?: AbortSignal;
|
|
46
|
+
readonly requestId?: string;
|
|
47
|
+
readonly sessionId?: string;
|
|
48
|
+
readonly principal?: Principal;
|
|
49
|
+
readonly attributes?: McpAttributes;
|
|
50
|
+
}
|
|
51
|
+
/** An input payload paired with the context propagated through its execution. */
|
|
52
|
+
interface McpOperation<Input = unknown, Context extends McpOperationContext = McpOperationContext> {
|
|
53
|
+
readonly input: Input;
|
|
54
|
+
readonly context: Context;
|
|
55
|
+
}
|
|
56
|
+
/** The terminal function at the end of an operation middleware chain. */
|
|
57
|
+
type McpOperationHandler<Input = unknown, Output = unknown, Context extends McpOperationContext = McpOperationContext> = (operation: McpOperation<Input, Context>) => MaybePromise<Output>;
|
|
58
|
+
/** Continuation supplied to operation middleware. It may be invoked at most once. */
|
|
59
|
+
type McpOperationNext<Output = unknown> = () => Promise<Output>;
|
|
60
|
+
/** Middleware that surrounds the next stage of an operation. */
|
|
61
|
+
type McpOperationMiddleware<Input = unknown, Output = unknown, Context extends McpOperationContext = McpOperationContext> = (operation: McpOperation<Input, Context>, next: McpOperationNext<Output>) => MaybePromise<Output>;
|
|
62
|
+
/**
|
|
63
|
+
* Creates a shallowly immutable context and copies both attribute maps so later
|
|
64
|
+
* caller mutation cannot alter routing, authorization, or telemetry dimensions.
|
|
65
|
+
*/
|
|
66
|
+
declare function createMcpOperationContext<Principal = unknown>(init: McpOperationContextInit<Principal>): McpOperationContext<Principal>;
|
|
67
|
+
/** Creates an immutable operation envelope without cloning its potentially large input. */
|
|
68
|
+
declare function createMcpOperation<Input, Context extends McpOperationContext = McpOperationContext>(input: Input, context: Context): McpOperation<Input, Context>;
|
|
69
|
+
//#endregion
|
|
70
|
+
export { McpOperationHandler as a, McpOperationMiddleware as c, createMcpOperation as d, createMcpOperationContext as f, McpAttributes as h, McpOperationContextInit as i, McpOperationNext as l, McpAttributeValue as m, McpOperation as n, McpOperationKind as o, McpAttributeScalar as p, McpOperationContext as r, McpOperationMetadata as s, MaybePromise as t, McpRuntimeRole as u };
|
|
71
|
+
//# sourceMappingURL=operation-D33Ttxve.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operation-D33Ttxve.d.mts","names":[],"sources":["../src/attribute-values.ts","../src/operation.ts"],"mappings":";KAAY;;KAGA,oBAAoB,8BAA8B;;KAGlD,gBAAgB,SAAS,eAAe;;;;KCAxC,aAAa,SAAS,QAAQ,YAAY;;KAG1C;;KAGA;;UAGK;;WAEP;WACA,MAAM;;WAEN;;WAEA;WACA,YAAY;;;UAIL,oBAAoB;;WAE3B;WACA,MAAM;WACN,WAAW;WACX,QAAQ;WACR;WACA;WACA,YAAY;WACZ,YAAY;;;UAIL,wBAAwB;WAC/B;WACA,MAAM;WACN,WAAW,KAAK;aACf,aAAa;;WAEd,SAAS;WACT;WACA;WACA,YAAY;WACZ,aAAa;;;UAIN,aAChB,iBACA,gBAAgB,sBAAsB;WAE7B,OAAO;WACP,SAAS;;;KAIP,oBACX,iBACA,kBACA,gBAAgB,sBAAsB,wBAClC,WAAW,aAAa,OAAO,aAAa,aAAa;;KAGlD,iBAAiB,0BAA0B,QAAQ;;KAGnD,uBACX,iBACA,kBACA,gBAAgB,sBAAsB,wBAEtC,WAAW,aAAa,OAAO,UAC/B,MAAM,iBAAiB,YACnB,aAAa;;;;;iBAMF,0BAA0B,qBACzC,MAAM,wBAAwB,aAC5B,oBAAoB;;iBAiCP,mBACf,OACA,gBAAgB,sBAAsB,qBACrC,OAAO,OAAO,SAAS,UAAU,aAAa,OAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as McpOperationHandler, c as McpOperationMiddleware, d as createMcpOperation, f as createMcpOperationContext, h as McpAttributes, i as McpOperationContextInit, l as McpOperationNext, m as McpAttributeValue, n as McpOperation, o as McpOperationKind, p as McpAttributeScalar, r as McpOperationContext, s as McpOperationMetadata, t as MaybePromise, u as McpRuntimeRole } from "./operation-D33Ttxve.mjs";
|
|
2
|
+
export { MaybePromise, type McpAttributeScalar, type McpAttributeValue, type McpAttributes, McpOperation, McpOperationContext, McpOperationContextInit, McpOperationHandler, McpOperationKind, McpOperationMetadata, McpOperationMiddleware, McpOperationNext, McpRuntimeRole, createMcpOperation, createMcpOperationContext };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { t as copyMcpAttributes } from "./attribute-values-BO6aCUgL.mjs";
|
|
2
|
+
//#region src/operation.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates a shallowly immutable context and copies both attribute maps so later
|
|
5
|
+
* caller mutation cannot alter routing, authorization, or telemetry dimensions.
|
|
6
|
+
*/
|
|
7
|
+
function createMcpOperationContext(init) {
|
|
8
|
+
assertIdentifier(init.operationId, "operationId");
|
|
9
|
+
assertRuntimeRole(init.role);
|
|
10
|
+
assertIdentifier(init.operation.name, "operation.name");
|
|
11
|
+
assertOperationKind(init.operation.kind);
|
|
12
|
+
assertOptionalIdentifier(init.operation.capability, "operation.capability");
|
|
13
|
+
assertOptionalIdentifier(init.operation.target, "operation.target");
|
|
14
|
+
assertOptionalIdentifier(init.requestId, "requestId");
|
|
15
|
+
assertOptionalIdentifier(init.sessionId, "sessionId");
|
|
16
|
+
const operation = Object.freeze({
|
|
17
|
+
name: init.operation.name,
|
|
18
|
+
kind: init.operation.kind,
|
|
19
|
+
...init.operation.capability === void 0 ? {} : { capability: init.operation.capability },
|
|
20
|
+
...init.operation.target === void 0 ? {} : { target: init.operation.target },
|
|
21
|
+
attributes: copyMcpAttributes(init.operation.attributes, "operation.attributes")
|
|
22
|
+
});
|
|
23
|
+
const context = {
|
|
24
|
+
operationId: init.operationId,
|
|
25
|
+
role: init.role,
|
|
26
|
+
operation,
|
|
27
|
+
signal: init.signal ?? new AbortController().signal,
|
|
28
|
+
...init.requestId === void 0 ? {} : { requestId: init.requestId },
|
|
29
|
+
...init.sessionId === void 0 ? {} : { sessionId: init.sessionId },
|
|
30
|
+
...init.principal === void 0 ? {} : { principal: init.principal },
|
|
31
|
+
attributes: copyMcpAttributes(init.attributes, "attributes")
|
|
32
|
+
};
|
|
33
|
+
return Object.freeze(context);
|
|
34
|
+
}
|
|
35
|
+
/** Creates an immutable operation envelope without cloning its potentially large input. */
|
|
36
|
+
function createMcpOperation(input, context) {
|
|
37
|
+
return Object.freeze({
|
|
38
|
+
input,
|
|
39
|
+
context
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function assertRuntimeRole(role) {
|
|
43
|
+
if (role !== "client" && role !== "server" && role !== "gateway") throw new TypeError("role must be client, server, or gateway.");
|
|
44
|
+
}
|
|
45
|
+
function assertOperationKind(kind) {
|
|
46
|
+
if (kind !== "request" && kind !== "notification") throw new TypeError("operation.kind must be request or notification.");
|
|
47
|
+
}
|
|
48
|
+
function assertIdentifier(value, field) {
|
|
49
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${field} must be a non-empty string.`);
|
|
50
|
+
}
|
|
51
|
+
function assertOptionalIdentifier(value, field) {
|
|
52
|
+
if (value !== void 0) assertIdentifier(value, field);
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { createMcpOperation, createMcpOperationContext };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=operation.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operation.mjs","names":[],"sources":["../src/operation.ts"],"sourcesContent":["import { copyMcpAttributes } from \"./attribute-values.ts\";\nimport type { McpAttributeScalar, McpAttributes, McpAttributeValue } from \"./attribute-values.ts\";\n\nexport type { McpAttributeScalar, McpAttributes, McpAttributeValue };\n\n/** A value that may be produced synchronously or asynchronously. */\nexport type MaybePromise<Value> = Value | PromiseLike<Value>;\n\n/** The position at which an operation is running. */\nexport type McpRuntimeRole = \"client\" | \"server\" | \"gateway\";\n\n/** The protocol interaction represented by an operation. */\nexport type McpOperationKind = \"request\" | \"notification\";\n\n/** Stable metadata describing an operation independently of its input payload. */\nexport interface McpOperationMetadata {\n\t/** Protocol method or application-defined operation name. */\n\treadonly name: string;\n\treadonly kind: McpOperationKind;\n\t/** Optional capability family, such as `tools`, `resources`, or `prompts`. */\n\treadonly capability?: string;\n\t/** Optional logical target, such as an upstream server identifier. */\n\treadonly target?: string;\n\treadonly attributes: McpAttributes;\n}\n\n/** Immutable context propagated through one runtime operation. */\nexport interface McpOperationContext<Principal = unknown> {\n\t/** Runtime-unique identifier used to correlate logs and telemetry. */\n\treadonly operationId: string;\n\treadonly role: McpRuntimeRole;\n\treadonly operation: McpOperationMetadata;\n\treadonly signal: AbortSignal;\n\treadonly requestId?: string;\n\treadonly sessionId?: string;\n\treadonly principal?: Principal;\n\treadonly attributes: McpAttributes;\n}\n\n/** Input used to construct an immutable operation context. */\nexport interface McpOperationContextInit<Principal = unknown> {\n\treadonly operationId: string;\n\treadonly role: McpRuntimeRole;\n\treadonly operation: Omit<McpOperationMetadata, \"attributes\"> & {\n\t\treadonly attributes?: McpAttributes;\n\t};\n\treadonly signal?: AbortSignal;\n\treadonly requestId?: string;\n\treadonly sessionId?: string;\n\treadonly principal?: Principal;\n\treadonly attributes?: McpAttributes;\n}\n\n/** An input payload paired with the context propagated through its execution. */\nexport interface McpOperation<\n\tInput = unknown,\n\tContext extends McpOperationContext = McpOperationContext,\n> {\n\treadonly input: Input;\n\treadonly context: Context;\n}\n\n/** The terminal function at the end of an operation middleware chain. */\nexport type McpOperationHandler<\n\tInput = unknown,\n\tOutput = unknown,\n\tContext extends McpOperationContext = McpOperationContext,\n> = (operation: McpOperation<Input, Context>) => MaybePromise<Output>;\n\n/** Continuation supplied to operation middleware. It may be invoked at most once. */\nexport type McpOperationNext<Output = unknown> = () => Promise<Output>;\n\n/** Middleware that surrounds the next stage of an operation. */\nexport type McpOperationMiddleware<\n\tInput = unknown,\n\tOutput = unknown,\n\tContext extends McpOperationContext = McpOperationContext,\n> = (\n\toperation: McpOperation<Input, Context>,\n\tnext: McpOperationNext<Output>,\n) => MaybePromise<Output>;\n\n/**\n * Creates a shallowly immutable context and copies both attribute maps so later\n * caller mutation cannot alter routing, authorization, or telemetry dimensions.\n */\nexport function createMcpOperationContext<Principal = unknown>(\n\tinit: McpOperationContextInit<Principal>,\n): McpOperationContext<Principal> {\n\tassertIdentifier(init.operationId, \"operationId\");\n\tassertRuntimeRole(init.role);\n\tassertIdentifier(init.operation.name, \"operation.name\");\n\tassertOperationKind(init.operation.kind);\n\tassertOptionalIdentifier(init.operation.capability, \"operation.capability\");\n\tassertOptionalIdentifier(init.operation.target, \"operation.target\");\n\tassertOptionalIdentifier(init.requestId, \"requestId\");\n\tassertOptionalIdentifier(init.sessionId, \"sessionId\");\n\n\tconst operation = Object.freeze({\n\t\tname: init.operation.name,\n\t\tkind: init.operation.kind,\n\t\t...(init.operation.capability === undefined ? {} : { capability: init.operation.capability }),\n\t\t...(init.operation.target === undefined ? {} : { target: init.operation.target }),\n\t\tattributes: copyMcpAttributes(init.operation.attributes, \"operation.attributes\"),\n\t}) satisfies McpOperationMetadata;\n\n\tconst context = {\n\t\toperationId: init.operationId,\n\t\trole: init.role,\n\t\toperation,\n\t\tsignal: init.signal ?? new AbortController().signal,\n\t\t...(init.requestId === undefined ? {} : { requestId: init.requestId }),\n\t\t...(init.sessionId === undefined ? {} : { sessionId: init.sessionId }),\n\t\t...(init.principal === undefined ? {} : { principal: init.principal }),\n\t\tattributes: copyMcpAttributes(init.attributes, \"attributes\"),\n\t} satisfies McpOperationContext<Principal>;\n\n\treturn Object.freeze(context);\n}\n\n/** Creates an immutable operation envelope without cloning its potentially large input. */\nexport function createMcpOperation<\n\tInput,\n\tContext extends McpOperationContext = McpOperationContext,\n>(input: Input, context: Context): McpOperation<Input, Context> {\n\treturn Object.freeze({ input, context });\n}\n\nfunction assertRuntimeRole(role: McpRuntimeRole): void {\n\tif (role !== \"client\" && role !== \"server\" && role !== \"gateway\") {\n\t\tthrow new TypeError(\"role must be client, server, or gateway.\");\n\t}\n}\n\nfunction assertOperationKind(kind: McpOperationKind): void {\n\tif (kind !== \"request\" && kind !== \"notification\") {\n\t\tthrow new TypeError(\"operation.kind must be request or notification.\");\n\t}\n}\n\nfunction assertIdentifier(value: string, field: string): void {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new TypeError(`${field} must be a non-empty string.`);\n\t}\n}\n\nfunction assertOptionalIdentifier(value: string | undefined, field: string): void {\n\tif (value !== undefined) assertIdentifier(value, field);\n}\n"],"mappings":";;;;;;AAsFA,SAAgB,0BACf,MACiC;CACjC,iBAAiB,KAAK,aAAa,aAAa;CAChD,kBAAkB,KAAK,IAAI;CAC3B,iBAAiB,KAAK,UAAU,MAAM,gBAAgB;CACtD,oBAAoB,KAAK,UAAU,IAAI;CACvC,yBAAyB,KAAK,UAAU,YAAY,sBAAsB;CAC1E,yBAAyB,KAAK,UAAU,QAAQ,kBAAkB;CAClE,yBAAyB,KAAK,WAAW,WAAW;CACpD,yBAAyB,KAAK,WAAW,WAAW;CAEpD,MAAM,YAAY,OAAO,OAAO;EAC/B,MAAM,KAAK,UAAU;EACrB,MAAM,KAAK,UAAU;EACrB,GAAI,KAAK,UAAU,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,KAAK,UAAU,WAAW;EAC3F,GAAI,KAAK,UAAU,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,KAAK,UAAU,OAAO;EAC/E,YAAY,kBAAkB,KAAK,UAAU,YAAY,sBAAsB;CAChF,CAAC;CAED,MAAM,UAAU;EACf,aAAa,KAAK;EAClB,MAAM,KAAK;EACX;EACA,QAAQ,KAAK,UAAU,IAAI,gBAAgB,CAAC,CAAC;EAC7C,GAAI,KAAK,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,KAAK,UAAU;EACpE,GAAI,KAAK,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,KAAK,UAAU;EACpE,GAAI,KAAK,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,KAAK,UAAU;EACpE,YAAY,kBAAkB,KAAK,YAAY,YAAY;CAC5D;CAEA,OAAO,OAAO,OAAO,OAAO;AAC7B;;AAGA,SAAgB,mBAGd,OAAc,SAAgD;CAC/D,OAAO,OAAO,OAAO;EAAE;EAAO;CAAQ,CAAC;AACxC;AAEA,SAAS,kBAAkB,MAA4B;CACtD,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACtD,MAAM,IAAI,UAAU,0CAA0C;AAEhE;AAEA,SAAS,oBAAoB,MAA8B;CAC1D,IAAI,SAAS,aAAa,SAAS,gBAClC,MAAM,IAAI,UAAU,iDAAiD;AAEvE;AAEA,SAAS,iBAAiB,OAAe,OAAqB;CAC7D,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW,GACxD,MAAM,IAAI,UAAU,GAAG,MAAM,6BAA6B;AAE5D;AAEA,SAAS,yBAAyB,OAA2B,OAAqB;CACjF,IAAI,UAAU,KAAA,GAAW,iBAAiB,OAAO,KAAK;AACvD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,82 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-mcp/core",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "2.0.0-alpha.0",
|
|
4
|
+
"description": "Framework-neutral runtime primitives for composing MCP clients, servers, and gateways.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/btwld/nest-mcp.git",
|
|
8
|
+
"directory": "packages/core"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/btwld/nest-mcp/tree/main/packages/core#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/btwld/nest-mcp/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"mcp",
|
|
16
|
+
"model-context-protocol",
|
|
17
|
+
"runtime",
|
|
18
|
+
"middleware",
|
|
19
|
+
"authorization",
|
|
20
|
+
"observability",
|
|
21
|
+
"esm",
|
|
22
|
+
"nest-mcp"
|
|
23
|
+
],
|
|
24
|
+
"license": "BSD-3-Clause",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.13.0"
|
|
29
|
+
},
|
|
30
|
+
"types": "./dist/index.d.mts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.mts",
|
|
34
|
+
"import": "./dist/index.mjs",
|
|
35
|
+
"default": "./dist/index.mjs"
|
|
36
|
+
},
|
|
37
|
+
"./authorization": {
|
|
38
|
+
"types": "./dist/authorization.d.mts",
|
|
39
|
+
"import": "./dist/authorization.mjs",
|
|
40
|
+
"default": "./dist/authorization.mjs"
|
|
41
|
+
},
|
|
42
|
+
"./lifecycle": {
|
|
43
|
+
"types": "./dist/lifecycle.d.mts",
|
|
44
|
+
"import": "./dist/lifecycle.mjs",
|
|
45
|
+
"default": "./dist/lifecycle.mjs"
|
|
46
|
+
},
|
|
47
|
+
"./middleware": {
|
|
48
|
+
"types": "./dist/middleware.d.mts",
|
|
49
|
+
"import": "./dist/middleware.mjs",
|
|
50
|
+
"default": "./dist/middleware.mjs"
|
|
51
|
+
},
|
|
52
|
+
"./operation": {
|
|
53
|
+
"types": "./dist/operation.d.mts",
|
|
54
|
+
"import": "./dist/operation.mjs",
|
|
55
|
+
"default": "./dist/operation.mjs"
|
|
56
|
+
},
|
|
57
|
+
"./package.json": "./package.json"
|
|
58
|
+
},
|
|
59
|
+
"files": [
|
|
60
|
+
"dist",
|
|
61
|
+
"README.md",
|
|
62
|
+
"CHANGELOG.md",
|
|
63
|
+
"LICENSE"
|
|
64
|
+
],
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public",
|
|
67
|
+
"provenance": true
|
|
68
|
+
},
|
|
69
|
+
"scripts": {
|
|
70
|
+
"build": "tsdown",
|
|
71
|
+
"build:watch": "tsdown --watch src",
|
|
72
|
+
"typecheck": "tsc -b",
|
|
73
|
+
"lint": "oxlint --type-aware .",
|
|
74
|
+
"lint:fix": "oxlint --type-aware --fix .",
|
|
75
|
+
"format": "prettier --write . --ignore-unknown",
|
|
76
|
+
"format:check": "prettier --check . --ignore-unknown",
|
|
77
|
+
"test": "vitest run",
|
|
78
|
+
"test:watch": "vitest",
|
|
79
|
+
"test:coverage": "vitest run --coverage",
|
|
80
|
+
"verify:pack": "pnpm run build && publint --strict"
|
|
81
|
+
}
|
|
6
82
|
}
|