@vesta-analytics/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @vesta-analytics/sdk (TypeScript)
2
+
3
+ Customer-installable SDK. One call instruments an MCP server and ships
4
+ behavioural data to Vesta over OTLP/HTTP — the **same wire format** as the
5
+ Python `vesta-analytics`, so SDK-emitted rows land in `raw.spans` indistinguishable
6
+ from any other producer.
7
+
8
+ ```bash
9
+ npm install @vesta-analytics/sdk
10
+ ```
11
+
12
+ ```ts
13
+ import { instrument } from '@vesta-analytics/sdk';
14
+ instrument(server, { apiKey: 'vsk_...' });
15
+ ```
16
+
17
+ Runs inside the customer's process — minimal footprint, fail-open, never breaks
18
+ the host server. Entry point: `src/instrument.ts`. Build with `npm run build`,
19
+ test with `npm test` (vitest).
20
+
21
+ ## What it supports
22
+
23
+ - **Official `@modelcontextprotocol/sdk`** — both the low-level `Server` and the
24
+ high-level `McpServer` (wrapped via its `.server`).
25
+ - **Community `fastmcp`** — wraps each session's underlying server as it
26
+ connects (fastmcp creates the server per-session).
27
+
28
+ Detection is structural (duck-typed), so the MCP packages are optional peer
29
+ dependencies — install only the framework you use.
30
+
31
+ ## Usage
32
+
33
+ ```ts
34
+ import { instrument, RedactionConfig, Field, Tool } from '@vesta-analytics/sdk';
35
+
36
+ instrument(server, {
37
+ apiKey: 'vsk_...',
38
+ endpoint: 'https://ingest.vesta-analytics.ai/v1/traces', // default
39
+ verbose: false,
40
+ // Redaction defaults to "redact" everything; opt into capture explicitly.
41
+ args: new RedactionConfig({
42
+ default: 'capture',
43
+ rules: [Field('password').redact(), Field('email').hash(), Tool('pay_*').redact()],
44
+ }),
45
+ responses: new RedactionConfig({ default: 'capture' }),
46
+ sessionContext: (extra) => ({ user_id: getUserId(extra), plan: getPlan(extra) }),
47
+ });
48
+ ```
49
+
50
+ Add the call **after tools are registered and before you serve** — the adapter
51
+ skips wrapping a method whose handler is not registered yet.
52
+
53
+ ## Parity with the Python SDK
54
+
55
+ This is a structural 1:1 port of `packages/vesta-sdk`. The framework-free core
56
+ (`capture`, `redaction`, `propagation`, `dimensions`, `export`, `diagnostics`)
57
+ mirrors the Python modules, and the wire output is produced by the OpenTelemetry
58
+ JS SDK + OTLP-proto-HTTP exporter, matching Python's OTLP/protobuf bytes.
59
+
60
+ Spans are deliberately distinguishable by producing SDK: the TypeScript SDK
61
+ stamps `agent_runtime = "vesta-sdk-js"` (the Python SDK uses `"vesta-sdk"`),
62
+ following the existing `vesta-<runtime>` convention. Everything else — columns,
63
+ payload encoding, `source_kind="sdk"` — is identical, so analyses that don't
64
+ care about language treat the rows the same.
65
+
66
+ Two intentional differences from Python:
67
+
68
+ - **Session id is real.** The official TS SDK hands the request handler an
69
+ `extra.sessionId` (transport session id), used directly. Python had no stable
70
+ session id and fell back to `id(session)`. A missing id still resolves
71
+ dimensions fresh per call (the cross-user privacy invariant).
72
+ - **`hash` redaction matches for common scalars only.** The action hashes
73
+ `sha256(pythonRepr(value))[:16]`; `pythonRepr` replicates Python's `repr()`
74
+ for strings/numbers/bools/null (verified against ground-truth digests), so
75
+ hashes agree cross-SDK for typical PII. Exotic types may diverge.
76
+
77
+ ## Shutdown / stdio delivery
78
+
79
+ `instrument()` installs a bounded flush on process shutdown: it hooks
80
+ `process.stdin`'s `end` (the MCP stdio transport doesn't surface EOF itself),
81
+ `SIGTERM`, and `SIGINT`. This matters most for stdio MCP servers — short
82
+ sessions export nothing until shutdown, so the flush is the whole delivery path.
83
+ On a signal the SDK only force-exits when it is the sole listener, so it never
84
+ cuts short an HTTP server's graceful drain. Exit is hard-bounded (default 2s,
85
+ `VESTA_FLUSH_DEADLINE_MS` to override). `instrument()` returns an
86
+ `InstrumentHandle` with `flush()` / `shutdown()` for custom lifecycles; ignoring
87
+ it is fine. Every span carries a best-effort `vesta.transport` label (override
88
+ with the `transport` option or `VESTA_TRANSPORT`).
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Adapter protocol — the ONLY framework-coupled seam.
3
+ *
4
+ * An adapter does exactly three things:
5
+ * 1. detect whether it owns a given server object,
6
+ * 2. wrap the MCP request handlers so the SDK runs around them,
7
+ * 3. expose the framework request object + JSON-RPC params to the SDK.
8
+ *
9
+ * Everything else (capture, redaction, dimensions, export) is framework-free.
10
+ */
11
+ export interface Invocation {
12
+ /** MCP method: "tools/call", "prompts/get", "resources/read", "initialize", "tools/list", … */
13
+ method: string;
14
+ /** The addressable identity — tool name, prompt name, or resource URI;
15
+ * `method` discriminates. Empty string for methods without a target. */
16
+ toolName: string;
17
+ /** Request payload. */
18
+ arguments: unknown;
19
+ /** Raw JSON-RPC params (carries `_meta`). */
20
+ params: unknown;
21
+ /** Framework request object (the handler `extra`), for sessionContext. */
22
+ request: unknown;
23
+ sessionId: string | null;
24
+ /** Customer handler return value (post-transform); null if not captured. */
25
+ result?: unknown;
26
+ /** Method-specific flat span attributes (e.g. mcp.client.name on initialize). */
27
+ extraAttributes?: Record<string, unknown> | null;
28
+ /** Phase 1 latency: epoch ms at handler start; used as the span start time. */
29
+ startTime?: number;
30
+ /** Monotonic handler execution duration in ms; span end = startTime + durationMs. */
31
+ durationMs?: number;
32
+ /** Handler threw/timed out: span gets ERROR status and no result. */
33
+ isError?: boolean;
34
+ }
35
+ export type OnInvocation = (inv: Invocation) => void;
36
+ export interface Adapter {
37
+ readonly name: string;
38
+ owns(server: unknown): boolean;
39
+ wrap(server: unknown, onInvocation: OnInvocation): void;
40
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Adapter protocol — the ONLY framework-coupled seam.
3
+ *
4
+ * An adapter does exactly three things:
5
+ * 1. detect whether it owns a given server object,
6
+ * 2. wrap the MCP request handlers so the SDK runs around them,
7
+ * 3. expose the framework request object + JSON-RPC params to the SDK.
8
+ *
9
+ * Everything else (capture, redaction, dimensions, export) is framework-free.
10
+ */
11
+ export {};
@@ -0,0 +1,18 @@
1
+ /**
2
+ * FastMcpAdapter — instruments the community `fastmcp` package (punkpeye).
3
+ *
4
+ * Unlike the official SDK, `fastmcp` creates the underlying official `Server`
5
+ * per connection inside a `FastMCPSession` (held in a true-private `#server`
6
+ * field, reachable only via the session's public `.server` getter). So there
7
+ * is no single handler map to wrap at install time. Instead the adapter wraps
8
+ * every already-connected session and subscribes to the FastMCP `"connect"`
9
+ * event to wrap sessions as they appear.
10
+ *
11
+ * Importing this module never hard-requires `fastmcp`; detection is structural.
12
+ */
13
+ import type { Adapter, OnInvocation } from './base.js';
14
+ export declare class FastMcpAdapter implements Adapter {
15
+ readonly name = "fastmcp";
16
+ owns(server: unknown): boolean;
17
+ wrap(server: unknown, onInvocation: OnInvocation): void;
18
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * FastMcpAdapter — instruments the community `fastmcp` package (punkpeye).
3
+ *
4
+ * Unlike the official SDK, `fastmcp` creates the underlying official `Server`
5
+ * per connection inside a `FastMCPSession` (held in a true-private `#server`
6
+ * field, reachable only via the session's public `.server` getter). So there
7
+ * is no single handler map to wrap at install time. Instead the adapter wraps
8
+ * every already-connected session and subscribes to the FastMCP `"connect"`
9
+ * event to wrap sessions as they appear.
10
+ *
11
+ * Importing this module never hard-requires `fastmcp`; detection is structural.
12
+ */
13
+ import { sdkLogger } from '../diagnostics.js';
14
+ import { installLowlevelWrap, isLowlevelServer, lowlevelHandlers } from './lowlevel.js';
15
+ const log = sdkLogger('fastmcp');
16
+ function looksLikeFastMcp(server) {
17
+ if (server === null || typeof server !== 'object')
18
+ return false;
19
+ const s = server;
20
+ return (typeof s['addTool'] === 'function' &&
21
+ typeof s['start'] === 'function' &&
22
+ typeof s['on'] === 'function');
23
+ }
24
+ export class FastMcpAdapter {
25
+ name = 'fastmcp';
26
+ owns(server) {
27
+ return looksLikeFastMcp(server);
28
+ }
29
+ wrap(server, onInvocation) {
30
+ if (!looksLikeFastMcp(server))
31
+ return;
32
+ const wrapSession = (session) => {
33
+ const low = session?.['server'];
34
+ if (isLowlevelServer(low)) {
35
+ const getClientInfo = () => low.getClientVersion?.();
36
+ installLowlevelWrap(lowlevelHandlers(low), 'fastmcp', onInvocation, undefined, getClientInfo);
37
+ }
38
+ else {
39
+ log.debug('fastmcp session has no low-level server; skipping');
40
+ }
41
+ };
42
+ // Wrap any sessions already connected at install time.
43
+ const existing = server['sessions'];
44
+ if (Array.isArray(existing)) {
45
+ for (const session of existing)
46
+ wrapSession(session);
47
+ }
48
+ // Wrap sessions created later. fastmcp emits "connect" with { session }.
49
+ server['on']('connect', (event) => {
50
+ wrapSession(event?.session);
51
+ });
52
+ }
53
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Shared low-level MCP request-handler wrap logic.
3
+ *
4
+ * The official `@modelcontextprotocol/sdk` `Server` stores its handlers in a
5
+ * `Map<methodName, (request, extra) => result>` (`server._requestHandlers`).
6
+ * The high-level `McpServer` reaches the same map via `.server`, and a
7
+ * community `fastmcp` session reaches it via `session.server`. This helper
8
+ * holds the single wrap implementation so every adapter reuses it.
9
+ *
10
+ * Multi-method: callers pass `MethodSpec`s. Each handler that is actually
11
+ * registered gets wrapped; methods with no registered handler are skipped
12
+ * silently (a server need not implement every method).
13
+ *
14
+ * Not part of the public API; imported only by adapter modules.
15
+ */
16
+ import type { OnInvocation } from './base.js';
17
+ type Handler = (request: any, extra: any) => unknown | Promise<unknown>;
18
+ type HandlerMap = Map<string, Handler>;
19
+ export interface MethodSpec {
20
+ methodName: string;
21
+ /** Given the request, return [primaryId, argumentsObject]. */
22
+ extract: (request: any) => [string, unknown];
23
+ /** Given the customer's result, return a JSON-serialisable representation.
24
+ * TS SDK results are already plain objects, so this is identity by default. */
25
+ transformResult?: (result: any) => unknown;
26
+ /** Given (request, result), return flat method-specific span attributes. */
27
+ extractAttrs?: (request: any, result: any) => Record<string, unknown>;
28
+ }
29
+ /** The methods the SDK captures by default — every method we have an extractor
30
+ * for. Customers opt out of specific methods via RedactionConfig's Method(...)
31
+ * selector rather than a methods= option. */
32
+ export declare function defaultMethods(): MethodSpec[];
33
+ /** Wrap each registered method handler in `handlers`. Handlers not registered
34
+ * are skipped silently. on_invocation exceptions are swallowed; the customer
35
+ * result is always returned. */
36
+ export declare function installLowlevelWrap(handlers: HandlerMap, adapterName: string, onInvocation: OnInvocation, methods?: MethodSpec[], getClientInfo?: () => unknown): void;
37
+ /** Duck-type test for an official low-level `Server` (or anything exposing the
38
+ * same handler-map seam). */
39
+ export declare function isLowlevelServer(o: unknown): boolean;
40
+ export declare function lowlevelHandlers(o: unknown): HandlerMap;
41
+ export {};
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Shared low-level MCP request-handler wrap logic.
3
+ *
4
+ * The official `@modelcontextprotocol/sdk` `Server` stores its handlers in a
5
+ * `Map<methodName, (request, extra) => result>` (`server._requestHandlers`).
6
+ * The high-level `McpServer` reaches the same map via `.server`, and a
7
+ * community `fastmcp` session reaches it via `session.server`. This helper
8
+ * holds the single wrap implementation so every adapter reuses it.
9
+ *
10
+ * Multi-method: callers pass `MethodSpec`s. Each handler that is actually
11
+ * registered gets wrapped; methods with no registered handler are skipped
12
+ * silently (a server need not implement every method).
13
+ *
14
+ * Not part of the public API; imported only by adapter modules.
15
+ */
16
+ import { argumentShapeAttrs, authIdentityAttrs, baggageModelAttrs, clientIdentityAttrs, handshakeContractAttrs, resultShapeAttrs, } from '../capture.js';
17
+ import { sdkLogger } from '../diagnostics.js';
18
+ const log = sdkLogger('adapter');
19
+ const identity = (x) => x;
20
+ const noExtra = () => ({});
21
+ function extractToolsCall(req) {
22
+ return [req?.params?.name ?? '', req?.params?.arguments];
23
+ }
24
+ /** Privacy-safe per-call shape signals for tools/call: result shape (isError /
25
+ * structuredContent / content types) + argument key shape. Lands in
26
+ * raw_attributes (no schema migration). Mirror of the Python extractor. */
27
+ function extractToolsCallAttrs(req, result) {
28
+ return { ...resultShapeAttrs(result), ...argumentShapeAttrs(req?.params?.arguments) };
29
+ }
30
+ function extractPromptsGet(req) {
31
+ return [req?.params?.name ?? '', req?.params?.arguments];
32
+ }
33
+ function extractResourcesRead(req) {
34
+ const uri = String(req?.params?.uri ?? '');
35
+ return [uri, { uri }];
36
+ }
37
+ function extractInitialize(req) {
38
+ // No addressable target — primaryId is empty. Arguments = the request params.
39
+ return ['', req?.params ?? {}];
40
+ }
41
+ function extractInitializeAttrs(req, result) {
42
+ const attrs = {};
43
+ const clientInfo = req?.params?.clientInfo;
44
+ if (clientInfo) {
45
+ if (clientInfo.name)
46
+ attrs['mcp.client.name'] = clientInfo.name;
47
+ if (clientInfo.version)
48
+ attrs['mcp.client.version'] = clientInfo.version;
49
+ }
50
+ if (req?.params?.protocolVersion)
51
+ attrs['mcp.protocol.version'] = req.params.protocolVersion;
52
+ const serverInfo = result?.serverInfo;
53
+ if (serverInfo) {
54
+ if (serverInfo.name)
55
+ attrs['mcp.server.name'] = serverInfo.name;
56
+ if (serverInfo.version)
57
+ attrs['mcp.server.version'] = serverInfo.version;
58
+ }
59
+ // The negotiated contract: capability matrix + whether the server shipped
60
+ // natural-language `instructions` (an editable lever Vesta targets).
61
+ return { ...attrs, ...handshakeContractAttrs(req?.params, result) };
62
+ }
63
+ function extractListRequest(req) {
64
+ const cursor = req?.params?.cursor;
65
+ return ['', cursor !== undefined && cursor !== null ? { cursor } : {}];
66
+ }
67
+ function listAttrsFactory(itemsField) {
68
+ return (_req, result) => {
69
+ const items = result?.[itemsField] ?? [];
70
+ const nextCursor = result?.nextCursor;
71
+ const attrs = {
72
+ 'mcp.list.count': Array.isArray(items) ? items.length : 0,
73
+ 'mcp.list.has_more': nextCursor !== undefined && nextCursor !== null,
74
+ };
75
+ if (nextCursor !== undefined && nextCursor !== null)
76
+ attrs['mcp.list.cursor'] = nextCursor;
77
+ return attrs;
78
+ };
79
+ }
80
+ /** The methods the SDK captures by default — every method we have an extractor
81
+ * for. Customers opt out of specific methods via RedactionConfig's Method(...)
82
+ * selector rather than a methods= option. */
83
+ export function defaultMethods() {
84
+ return [
85
+ { methodName: 'tools/call', extract: extractToolsCall, extractAttrs: extractToolsCallAttrs },
86
+ { methodName: 'prompts/get', extract: extractPromptsGet },
87
+ { methodName: 'resources/read', extract: extractResourcesRead },
88
+ { methodName: 'initialize', extract: extractInitialize, extractAttrs: extractInitializeAttrs },
89
+ { methodName: 'tools/list', extract: extractListRequest, extractAttrs: listAttrsFactory('tools') },
90
+ { methodName: 'prompts/list', extract: extractListRequest, extractAttrs: listAttrsFactory('prompts') },
91
+ { methodName: 'resources/list', extract: extractListRequest, extractAttrs: listAttrsFactory('resources') },
92
+ {
93
+ methodName: 'resources/templates/list',
94
+ extract: extractListRequest,
95
+ extractAttrs: listAttrsFactory('resourceTemplates'),
96
+ },
97
+ ];
98
+ }
99
+ function buildWrapped(original, spec, adapterName, onInvocation, getClientInfo) {
100
+ const transformResult = spec.transformResult ?? identity;
101
+ const extractAttrs = spec.extractAttrs ?? noExtra;
102
+ return async function wrapped(request, extra) {
103
+ const startTime = Date.now();
104
+ const startNs = process.hrtime.bigint();
105
+ let customerResult;
106
+ try {
107
+ customerResult = await original(request, extra);
108
+ }
109
+ catch (err) {
110
+ const durationMs = Number(process.hrtime.bigint() - startNs) / 1e6;
111
+ try {
112
+ const [primaryId, args] = spec.extract(request);
113
+ const inv = {
114
+ method: spec.methodName,
115
+ toolName: primaryId,
116
+ arguments: args,
117
+ params: request?.params ?? null,
118
+ request: extra,
119
+ sessionId: extra?.sessionId ?? null,
120
+ result: null,
121
+ extraAttributes: null,
122
+ startTime,
123
+ durationMs,
124
+ isError: true,
125
+ };
126
+ onInvocation(inv);
127
+ }
128
+ catch (captureErr) {
129
+ log.debug(`error-span capture raised in ${adapterName} adapter for ${spec.methodName}; customer error preserved`, captureErr);
130
+ }
131
+ throw err;
132
+ }
133
+ const durationMs = Number(process.hrtime.bigint() - startNs) / 1e6;
134
+ try {
135
+ const sessionId = extra?.sessionId ?? null;
136
+ const [primaryId, args] = spec.extract(request);
137
+ const transformed = transformResult(customerResult);
138
+ // Per-method shape signals + per-call identity. Client app identity (which
139
+ // agent app — from the connection's negotiated clientInfo, on EVERY call)
140
+ // and model identity (lifted from request _meta baggage when an
141
+ // instrumented client propagates it). Auth identity (user_id/scopes from
142
+ // `extra.authInfo`) merged last. No key collides; all fail-open.
143
+ const attrs = {
144
+ ...extractAttrs(request, customerResult),
145
+ ...clientIdentityAttrs(getClientInfo?.()),
146
+ ...baggageModelAttrs(request?.params?._meta),
147
+ ...authIdentityAttrs(extra?.authInfo),
148
+ };
149
+ const inv = {
150
+ method: spec.methodName,
151
+ toolName: primaryId,
152
+ arguments: args,
153
+ params: request?.params ?? null,
154
+ request: extra,
155
+ sessionId,
156
+ result: transformed,
157
+ extraAttributes: Object.keys(attrs).length > 0 ? attrs : null,
158
+ startTime,
159
+ durationMs,
160
+ };
161
+ onInvocation(inv);
162
+ }
163
+ catch (err) {
164
+ log.debug(`on_invocation raised in ${adapterName} adapter for ${spec.methodName}; customer result preserved`, err);
165
+ }
166
+ return customerResult;
167
+ };
168
+ }
169
+ /** Wrap each registered method handler in `handlers`. Handlers not registered
170
+ * are skipped silently. on_invocation exceptions are swallowed; the customer
171
+ * result is always returned. */
172
+ export function installLowlevelWrap(handlers, adapterName, onInvocation, methods, getClientInfo) {
173
+ const specs = methods ?? defaultMethods();
174
+ for (const spec of specs) {
175
+ const original = handlers.get(spec.methodName);
176
+ if (original === undefined) {
177
+ log.debug(`${adapterName} adapter: no handler registered for ${spec.methodName}; skipping wrap`);
178
+ continue;
179
+ }
180
+ handlers.set(spec.methodName, buildWrapped(original, spec, adapterName, onInvocation, getClientInfo));
181
+ }
182
+ }
183
+ /** Duck-type test for an official low-level `Server` (or anything exposing the
184
+ * same handler-map seam). */
185
+ export function isLowlevelServer(o) {
186
+ if (o === null || typeof o !== 'object')
187
+ return false;
188
+ const rec = o;
189
+ return rec['_requestHandlers'] instanceof Map && typeof rec['setRequestHandler'] === 'function';
190
+ }
191
+ export function lowlevelHandlers(o) {
192
+ return o['_requestHandlers'];
193
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * McpAdapter — instruments the official `@modelcontextprotocol/sdk`.
3
+ *
4
+ * Covers both shapes a customer uses:
5
+ * - the low-level `Server` (`server/index.js`), and
6
+ * - the high-level `McpServer` (`server/mcp.js`), which wraps a low-level
7
+ * `Server` reachable via `.server`.
8
+ *
9
+ * Both expose the same `_requestHandlers` map, so the shared
10
+ * `installLowlevelWrap` handles them identically.
11
+ *
12
+ * Importing this module never hard-requires `@modelcontextprotocol/sdk`; it is
13
+ * an optional peer dependency. Detection is purely structural.
14
+ */
15
+ import type { Adapter, OnInvocation } from './base.js';
16
+ export declare class McpAdapter implements Adapter {
17
+ readonly name = "mcp";
18
+ owns(server: unknown): boolean;
19
+ wrap(server: unknown, onInvocation: OnInvocation): void;
20
+ }