Repository navigation
Expand file tree
/
Copy pathmcp.int.test.ts
More file actions
168 lines (154 loc) · 6.58 KB
/
Copy pathmcp.int.test.ts
File metadata and controls
168 lines (154 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// An agent that calls a wallet tool of an MCP server over stdio, as in docs/integrations.md: the server is a child
// process of the agent, which is a child process of this test, so no context crosses between them in memory. Both
// processes start the OpenTelemetry Node SDK and export over OTLP (JSON) to a receiver in this file; the server's
// tool sends on this file's Anvil. The test checks the parent of the server's `send` span:
// - without propagation (v1 SDK), `send` is the root of a trace of its own. This shows the setup can tell an
// orphan from a child, so the other two results mean something;
// - with OpenInference's MCP instrumentation (v1 SDK, readme/mcp-instrumentation.ts) and with the hand-written
// `_meta` propagation of the v2 SDK (readme/mcp-client.ts and readme/mcp-server.ts, run as written), `send` and
// `confirm` are children of the agent's `pay_vendor` span.
import { execFile } from 'node:child_process';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { promisify } from 'node:util';
import { foundry } from 'viem/chains';
import { afterAll, beforeEach, describe, expect, it } from 'vitest';
import { startAnvil } from '../../packages/viem/test/start-anvil.js';
type ReceivedSpan = {
service: string;
name: string;
traceId: string;
spanId: string;
parentSpanId: string | undefined;
attributes: Record<string, unknown>;
};
type OtlpValue = { stringValue?: string; intValue?: string; boolValue?: boolean };
type OtlpAttribute = { key: string; value: OtlpValue };
type OtlpTraces = {
resourceSpans?: {
resource?: { attributes?: OtlpAttribute[] };
scopeSpans?: {
spans?: {
name: string;
traceId: string;
spanId: string;
parentSpanId?: string;
attributes?: OtlpAttribute[];
}[];
}[];
}[];
};
const attributeValue = (value: OtlpValue) => value.stringValue ?? value.intValue ?? value.boolValue;
const attributesOf = (attributes: OtlpAttribute[] = []) =>
Object.fromEntries(attributes.map(({ key, value }) => [key, attributeValue(value)]));
// The OTLP/HTTP receiver: keeps the spans of every export, answers metrics and logs too.
const received: ReceivedSpan[] = [];
const receiver = createServer((request, response) => {
let body = '';
request.setEncoding('utf8');
request.on('data', (chunk: string) => {
body += chunk;
});
request.on('end', () => {
if (request.url === '/v1/traces') {
for (const resourceSpans of (JSON.parse(body) as OtlpTraces).resourceSpans ?? []) {
const service = attributesOf(resourceSpans.resource?.attributes)['service.name'];
for (const scopeSpans of resourceSpans.scopeSpans ?? [])
for (const span of scopeSpans.spans ?? [])
received.push({
service: String(service),
name: span.name,
traceId: span.traceId,
spanId: span.spanId,
parentSpanId: span.parentSpanId || undefined,
attributes: attributesOf(span.attributes),
});
}
}
response.writeHead(200, { 'content-type': 'application/json' });
response.end('{}');
});
});
await new Promise<void>((resolve) => receiver.listen(0, '127.0.0.1', resolve));
const otlpEndpoint = `http://127.0.0.1:${(receiver.address() as AddressInfo).port}`;
const { instance, rpcUrl } = await startAnvil({
binary: new URL('../../.tools/bin/anvil', import.meta.url).pathname,
chainId: foundry.id,
});
afterAll(async () => {
await new Promise((resolve) => receiver.close(resolve));
await instance.stop();
});
beforeEach(() => {
received.length = 0;
});
/**
* Runs an agent file with tsx's loader, from integrations/ so that tsx maps `@hashspan/*` to their sources
* (tsconfig.json), and returns what it printed once both processes have exited.
*/
async function runAgent(file: string, env: Record<string, string> = {}): Promise<string> {
const { stdout } = await promisify(execFile)(
process.execPath,
['--import', 'tsx', new URL(file, import.meta.url).pathname],
{
cwd: new URL('..', import.meta.url).pathname,
env: {
...process.env,
RPC_URL: rpcUrl,
OTEL_EXPORTER_OTLP_ENDPOINT: otlpEndpoint,
OTEL_EXPORTER_OTLP_PROTOCOL: 'http/json',
OTEL_METRICS_EXPORTER: 'none',
OTEL_LOGS_EXPORTER: 'none',
...env,
},
timeout: 50_000,
},
);
return stdout;
}
const chainSpan = (kind: 'send' | 'confirm') => `${kind} ${foundry.id}`;
/** The agent's tool span and the server's send and confirm spans, one of each. */
function spansOfRun(): Record<'tool' | 'send' | 'confirm', ReceivedSpan> {
const one = (service: string, name: string) => {
const spans = received.filter((span) => span.service === service && span.name === name);
expect(spans, `${service} ${name} in [${received.map((s) => s.name)}]`).toHaveLength(1);
return spans[0] as ReceivedSpan;
};
return {
tool: one('my-agent', 'pay_vendor'),
send: one('wallet-mcp', chainSpan('send')),
confirm: one('wallet-mcp', chainSpan('confirm')),
};
}
function expectChildrenOfTool({ tool, send, confirm }: ReturnType<typeof spansOfRun>): void {
expect(tool.parentSpanId).toBeUndefined();
for (const span of [send, confirm]) {
expect(span.traceId).toBe(tool.traceId);
expect(span.parentSpanId).toBe(tool.spanId);
}
expect(confirm.attributes['blockchain.tx.hash']).toBe(send.attributes['blockchain.tx.hash']);
expect(confirm.attributes['blockchain.tx.status']).toBe('success');
}
describe('an MCP tool that sends a transaction, over stdio', () => {
it('starts a trace of its own without propagation (v1 SDK)', { timeout: 60_000 }, async () => {
expect(await runAgent('./mcp-v1/client.ts')).toMatch(/0x[0-9a-f]{64} success/);
const { tool, send, confirm } = spansOfRun();
expect(send.parentSpanId).toBeUndefined();
expect(send.traceId).not.toBe(tool.traceId);
expect(confirm.traceId).not.toBe(tool.traceId);
expect(confirm.attributes['blockchain.tx.hash']).toBe(send.attributes['blockchain.tx.hash']);
});
it('joins the agent trace with OpenInference MCP instrumentation (v1 SDK)', {
timeout: 60_000,
}, async () => {
const output = await runAgent('./mcp-v1/client.ts', { MCP_PROPAGATION: 'openinference' });
expect(output).toMatch(/0x[0-9a-f]{64} success/);
expectChildrenOfTool(spansOfRun());
});
it('joins the agent trace with _meta propagation by hand (v2 SDK, the docs example as written)', {
timeout: 60_000,
}, async () => {
expect(await runAgent('./readme/mcp-client.ts')).toMatch(/0x[0-9a-f]{64} success/);
expectChildrenOfTool(spansOfRun());
});
});