@smartbear/mcp 0.41.3 → 0.43.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/README.md +5 -0
- package/dist/bearq/api.js +16 -0
- package/dist/bearq/client.js +9 -1
- package/dist/bearq/tool/tasks/stop-task.js +6 -3
- package/dist/bearq/tool/workflows/get-workflow-run.js +31 -0
- package/dist/bearq/tool/workflows/list-workflows.js +28 -0
- package/dist/bearq/tool/workflows/run-workflow.js +57 -0
- package/dist/bearq/tool/workflows/stop-workflow-run.js +33 -0
- package/dist/bugsnag/client.js +1 -0
- package/dist/common/analytics.js +341 -0
- package/dist/common/initialize.js +1 -0
- package/dist/common/jwt.js +83 -0
- package/dist/common/register-clients.js +16 -18
- package/dist/common/server.js +36 -0
- package/dist/common/transport-http.js +48 -7
- package/dist/package.json.js +1 -1
- package/dist/pactflow/client/admin-api.js +3 -8
- package/dist/pactflow/client/ai.js +34 -0
- package/dist/pactflow/client/contract-api.js +2 -0
- package/dist/pactflow/client/http-client.js +7 -2
- package/dist/pactflow/client/pacticipant-api.js +37 -0
- package/dist/pactflow/client/pagination.js +1 -1
- package/dist/pactflow/client/schemas/admin.js +799 -0
- package/dist/pactflow/client/schemas/common.js +201 -0
- package/dist/pactflow/client/schemas/contract.js +444 -0
- package/dist/pactflow/client/schemas/environment.js +94 -0
- package/dist/pactflow/client/schemas/output.js +55 -0
- package/dist/pactflow/client/schemas/pacticipant.js +290 -0
- package/dist/pactflow/client/schemas/webhook.js +164 -0
- package/dist/pactflow/client/tools.js +32 -1
- package/dist/pactflow/client/utils.js +1 -1
- package/dist/pactflow/client.js +21 -3
- package/dist/qmetry/client/ai-agent.js +3 -0
- package/dist/qmetry/client/api/error-handler.js +7 -2
- package/dist/qmetry/client/auto-resolve.js +5 -0
- package/dist/qmetry/client/handlers.js +2 -1
- package/dist/qmetry/client/project.js +19 -1
- package/dist/qmetry/client/testsuite.js +207 -2
- package/dist/qmetry/client/tools/ai-agent-tools.js +13 -0
- package/dist/qmetry/client/tools/issue-tools.js +7 -3
- package/dist/qmetry/client/tools/project-tools.js +34 -1
- package/dist/qmetry/client/tools/testcase-tools.js +43 -296
- package/dist/qmetry/client/tools/testsuite-tools.js +49 -19
- package/dist/qmetry/client/udf.js +14 -2
- package/dist/qmetry/client.js +2 -1
- package/dist/qmetry/config/constants.js +1 -0
- package/dist/qmetry/config/rest-endpoints.js +2 -1
- package/dist/qmetry/types/ai-agent.js +3 -0
- package/dist/qmetry/types/common.js +40 -2
- package/dist/qmetry/types/udf.js +1 -20
- package/dist/qtm4j/client.js +1 -1
- package/dist/swagger/client/api.js +5 -1
- package/dist/swagger/client/portal-types.js +11 -5
- package/dist/swagger/client/registry-types.js +12 -5
- package/dist/swagger/client/tools.js +3 -3
- package/dist/zephyr/tool/issue-link/get-test-cases.js +1 -1
- package/dist/zephyr/tool/issue-link/get-test-cycles.js +1 -1
- package/dist/zephyr/tool/issue-link/get-test-executions.js +1 -1
- package/dist/zephyr/tool/test-case/update-test-case.js +1 -1
- package/dist/zephyr/tool/test-cycle/update-test-cycle.js +1 -1
- package/package.json +4 -3
- package/plugin/README.md +42 -0
- package/dist/pactflow/client/base.js +0 -488
package/README.md
CHANGED
|
@@ -315,12 +315,17 @@ Add the following configuration to your `claude_desktop_config.json` to launch t
|
|
|
315
315
|
}
|
|
316
316
|
```
|
|
317
317
|
|
|
318
|
+
### Loading only the products you use
|
|
319
|
+
|
|
320
|
+
Set `MCP_CLIENTS` to a comma-separated, case-insensitive list of product names (for example `"MCP_CLIENTS": "QMetry"`) to load only those products. This reduces startup time, which helps on clients with a short `initialize` timeout. Valid names are `BearQ`, `BugSnag`, `Collaborator`, `Contract Testing`, `QMetry`, `QTM4J`, `Reflect`, `Swagger` and `Zephyr`. When unset, all products are loaded.
|
|
321
|
+
|
|
318
322
|
## Server Configuration (HTTP mode)
|
|
319
323
|
|
|
320
324
|
| Variable | Default | Purpose |
|
|
321
325
|
|---|---|---|
|
|
322
326
|
| `BASE_URL` | *(derived from request)* | The server's own public URL, e.g. `https://mcp.example.com`. Set this on any deployment behind a proxy or load balancer — otherwise the address advertised for OAuth discovery is derived from the client-supplied `Host` header. |
|
|
323
327
|
| `TRUST_PROXY` | `false` | Set to `true` only when a proxy in front of the server sets `X-Forwarded-Host` and strips any client-supplied value. |
|
|
328
|
+
| `MCP_SERVER_AMPLITUDE_API_KEY` | *(unset — analytics off)* | API key for the shared SmartBear Amplitude project. When set, the server reports `Server Initialized`, `Session Started`, `Session Ended`, `Tool Called` and `Tools Listed` usage events (tool outcome and timing only — never tool arguments, results, credentials or raw email). Unset, nothing is tracked. HTTP mode only. |
|
|
324
329
|
|
|
325
330
|
## Documentation
|
|
326
331
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
async function toProblemDetail(res) {
|
|
2
|
+
try {
|
|
3
|
+
const body = await res.json();
|
|
4
|
+
return typeof body.detail === "string" && body.detail ? body.detail : null;
|
|
5
|
+
} catch {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
async function problemSuffix(res) {
|
|
10
|
+
const detail = await toProblemDetail(res);
|
|
11
|
+
return detail ? ` — ${detail}` : "";
|
|
12
|
+
}
|
|
13
|
+
export {
|
|
14
|
+
problemSuffix,
|
|
15
|
+
toProblemDetail
|
|
16
|
+
};
|
package/dist/bearq/client.js
CHANGED
|
@@ -14,6 +14,10 @@ import { RunTestCases } from "./tool/tasks/run-test-cases.js";
|
|
|
14
14
|
import { RunTestsInFunctionalAreas } from "./tool/tasks/run-tests-in-functional-areas.js";
|
|
15
15
|
import { StopTask } from "./tool/tasks/stop-task.js";
|
|
16
16
|
import { WaitForTask } from "./tool/tasks/wait-for-task.js";
|
|
17
|
+
import { GetWorkflowRun } from "./tool/workflows/get-workflow-run.js";
|
|
18
|
+
import { ListWorkflows } from "./tool/workflows/list-workflows.js";
|
|
19
|
+
import { RunWorkflow } from "./tool/workflows/run-workflow.js";
|
|
20
|
+
import { StopWorkflowRun } from "./tool/workflows/stop-workflow-run.js";
|
|
17
21
|
const ConfigurationSchema = z.object({
|
|
18
22
|
api_token: z.string().describe("BearQ workspace API token (Bearer)."),
|
|
19
23
|
api_base_url: z.string().optional().describe(
|
|
@@ -67,7 +71,11 @@ class BearQClient {
|
|
|
67
71
|
new GetTaskStatus(this),
|
|
68
72
|
new StopTask(this),
|
|
69
73
|
new WaitForTask(this),
|
|
70
|
-
new ListEnvironments(this)
|
|
74
|
+
new ListEnvironments(this),
|
|
75
|
+
new ListWorkflows(this),
|
|
76
|
+
new RunWorkflow(this),
|
|
77
|
+
new GetWorkflowRun(this),
|
|
78
|
+
new StopWorkflowRun(this)
|
|
71
79
|
];
|
|
72
80
|
for (const tool of tools) {
|
|
73
81
|
register(tool.specification, tool.handle);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { Tool, ToolError } from "../../../common/tools.js";
|
|
3
|
+
import { problemSuffix } from "../../api.js";
|
|
3
4
|
const inputSchema = z.object({
|
|
4
5
|
taskId: z.number().int().positive().describe("BearQ task ID to cancel.")
|
|
5
6
|
});
|
|
@@ -7,7 +8,7 @@ class StopTask extends Tool {
|
|
|
7
8
|
specification = {
|
|
8
9
|
title: "Stop Task",
|
|
9
10
|
toolset: "Tasks",
|
|
10
|
-
summary: "Cancels a running task.",
|
|
11
|
+
summary: "Cancels a pending or running task, returning { taskId, stopped: true }. The public API accepts a stop of an already-finished task as a success no-op, so this does not guarantee the task was running — check the task's status separately if that matters.",
|
|
11
12
|
inputSchema
|
|
12
13
|
};
|
|
13
14
|
handle = async (args) => {
|
|
@@ -18,10 +19,12 @@ class StopTask extends Tool {
|
|
|
18
19
|
});
|
|
19
20
|
if (!res.ok)
|
|
20
21
|
throw new ToolError(
|
|
21
|
-
`DELETE /tasks/${taskId} failed: ${res.status} ${res.statusText}`
|
|
22
|
+
`DELETE /tasks/${taskId} failed: ${res.status} ${res.statusText}` + await problemSuffix(res)
|
|
22
23
|
);
|
|
23
24
|
return {
|
|
24
|
-
content: [
|
|
25
|
+
content: [
|
|
26
|
+
{ type: "text", text: JSON.stringify({ taskId, stopped: true }) }
|
|
27
|
+
]
|
|
25
28
|
};
|
|
26
29
|
};
|
|
27
30
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Tool, ToolError } from "../../../common/tools.js";
|
|
3
|
+
const inputSchema = z.object({
|
|
4
|
+
runId: z.number().int().positive().describe("BearQ workflow run ID.")
|
|
5
|
+
});
|
|
6
|
+
class GetWorkflowRun extends Tool {
|
|
7
|
+
specification = {
|
|
8
|
+
title: "Get Workflow Run",
|
|
9
|
+
toolset: "Workflows",
|
|
10
|
+
summary: "Retrieves a workflow run's current status, per-step progress, and stats (tasks, tests, discovery, ACUs). Returns immediately with whatever's available — does not block on the run completing.",
|
|
11
|
+
inputSchema,
|
|
12
|
+
readOnly: true
|
|
13
|
+
};
|
|
14
|
+
handle = async (args) => {
|
|
15
|
+
const { runId } = inputSchema.parse(args);
|
|
16
|
+
const res = await fetch(
|
|
17
|
+
`${this.client.getBaseUrl()}/workflow-runs/${runId}`,
|
|
18
|
+
{ method: "GET", headers: this.client.getHeaders() }
|
|
19
|
+
);
|
|
20
|
+
if (!res.ok)
|
|
21
|
+
throw new ToolError(
|
|
22
|
+
`GET /workflow-runs/${runId} failed: ${res.status} ${res.statusText}`
|
|
23
|
+
);
|
|
24
|
+
return {
|
|
25
|
+
content: [{ type: "text", text: JSON.stringify(await res.json()) }]
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
GetWorkflowRun
|
|
31
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Tool, ToolError } from "../../../common/tools.js";
|
|
3
|
+
const inputSchema = z.object({});
|
|
4
|
+
class ListWorkflows extends Tool {
|
|
5
|
+
specification = {
|
|
6
|
+
title: "List Workflows",
|
|
7
|
+
toolset: "Workflows",
|
|
8
|
+
summary: "Lists the workflows in the workspace — each with its id, name, description, steps, and last run. Workspaces with more than 100 workflows are truncated; the response's totalCount says how many exist.",
|
|
9
|
+
inputSchema,
|
|
10
|
+
readOnly: true
|
|
11
|
+
};
|
|
12
|
+
handle = async (_args) => {
|
|
13
|
+
const res = await fetch(`${this.client.getBaseUrl()}/workflows?size=100`, {
|
|
14
|
+
method: "GET",
|
|
15
|
+
headers: this.client.getHeaders()
|
|
16
|
+
});
|
|
17
|
+
if (!res.ok)
|
|
18
|
+
throw new ToolError(
|
|
19
|
+
`GET /workflows failed: ${res.status} ${res.statusText}`
|
|
20
|
+
);
|
|
21
|
+
return {
|
|
22
|
+
content: [{ type: "text", text: JSON.stringify(await res.json()) }]
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
ListWorkflows
|
|
28
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Tool, ToolError } from "../../../common/tools.js";
|
|
3
|
+
const inputSchema = z.object({
|
|
4
|
+
workflow: z.string().min(1).describe(
|
|
5
|
+
"Workflow to run: its name (case-insensitive) or its numeric workflow ID."
|
|
6
|
+
)
|
|
7
|
+
});
|
|
8
|
+
async function resolveWorkflowId(client, workflow) {
|
|
9
|
+
if (/^\d+$/.test(workflow)) return Number(workflow);
|
|
10
|
+
const names = [];
|
|
11
|
+
for (let page = 1; ; page++) {
|
|
12
|
+
const res = await fetch(
|
|
13
|
+
`${client.getBaseUrl()}/workflows?page=${page}&size=100`,
|
|
14
|
+
{ method: "GET", headers: client.getHeaders() }
|
|
15
|
+
);
|
|
16
|
+
if (!res.ok)
|
|
17
|
+
throw new ToolError(
|
|
18
|
+
`GET /workflows failed: ${res.status} ${res.statusText}`
|
|
19
|
+
);
|
|
20
|
+
const body = await res.json();
|
|
21
|
+
const match = body.workflows.find(
|
|
22
|
+
(candidate) => candidate.name.toLowerCase() === workflow.toLowerCase().trim()
|
|
23
|
+
);
|
|
24
|
+
if (match) return match.id;
|
|
25
|
+
names.push(...body.workflows.map((candidate) => candidate.name));
|
|
26
|
+
if (body.workflows.length === 0 || names.length >= body.totalCount) break;
|
|
27
|
+
}
|
|
28
|
+
throw new ToolError(
|
|
29
|
+
`No BearQ workflow named "${workflow}". Available workflows: ${names.join(", ") || "(none)"}`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
class RunWorkflow extends Tool {
|
|
33
|
+
specification = {
|
|
34
|
+
title: "Run Workflow",
|
|
35
|
+
toolset: "Workflows",
|
|
36
|
+
summary: "Starts a run of a BearQ workflow now and returns the run (id, status, timestamps). If a run of that workflow is already in flight, no new run is started and the in-flight run is returned with started: false. Poll the run's progress with bearq_get_workflow_run.",
|
|
37
|
+
inputSchema
|
|
38
|
+
};
|
|
39
|
+
handle = async (args) => {
|
|
40
|
+
const { workflow } = inputSchema.parse(args);
|
|
41
|
+
const workflowId = await resolveWorkflowId(this.client, workflow);
|
|
42
|
+
const res = await fetch(
|
|
43
|
+
`${this.client.getBaseUrl()}/workflows/${workflowId}/runs`,
|
|
44
|
+
{ method: "POST", headers: this.client.getHeaders() }
|
|
45
|
+
);
|
|
46
|
+
if (!res.ok)
|
|
47
|
+
throw new ToolError(
|
|
48
|
+
`POST /workflows/${workflowId}/runs failed: ${res.status} ${res.statusText}`
|
|
49
|
+
);
|
|
50
|
+
return {
|
|
51
|
+
content: [{ type: "text", text: JSON.stringify(await res.json()) }]
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export {
|
|
56
|
+
RunWorkflow
|
|
57
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Tool, ToolError } from "../../../common/tools.js";
|
|
3
|
+
import { problemSuffix } from "../../api.js";
|
|
4
|
+
const inputSchema = z.object({
|
|
5
|
+
runId: z.number().int().positive().describe("BearQ workflow run ID to cancel.")
|
|
6
|
+
});
|
|
7
|
+
class StopWorkflowRun extends Tool {
|
|
8
|
+
specification = {
|
|
9
|
+
title: "Stop Workflow Run",
|
|
10
|
+
toolset: "Workflows",
|
|
11
|
+
summary: "Cancels a workflow run that is in flight, returning { runId, cancelled: true }. Fails with an error when the run has already finished or does not exist.",
|
|
12
|
+
inputSchema
|
|
13
|
+
};
|
|
14
|
+
handle = async (args) => {
|
|
15
|
+
const { runId } = inputSchema.parse(args);
|
|
16
|
+
const res = await fetch(
|
|
17
|
+
`${this.client.getBaseUrl()}/workflow-runs/${runId}`,
|
|
18
|
+
{ method: "DELETE", headers: this.client.getHeaders() }
|
|
19
|
+
);
|
|
20
|
+
if (!res.ok)
|
|
21
|
+
throw new ToolError(
|
|
22
|
+
`DELETE /workflow-runs/${runId} failed: ${res.status} ${res.statusText}` + await problemSuffix(res)
|
|
23
|
+
);
|
|
24
|
+
return {
|
|
25
|
+
content: [
|
|
26
|
+
{ type: "text", text: JSON.stringify({ runId, cancelled: true }) }
|
|
27
|
+
]
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
StopWorkflowRun
|
|
33
|
+
};
|
package/dist/bugsnag/client.js
CHANGED
|
@@ -124,6 +124,7 @@ class BugsnagClient {
|
|
|
124
124
|
configPrefix = "Bugsnag";
|
|
125
125
|
config = ConfigurationSchema;
|
|
126
126
|
defaultToolsets = ["Projects"];
|
|
127
|
+
analytics = { appName: "BugSnag", userId: ["sub"] };
|
|
127
128
|
async configure(_server, config) {
|
|
128
129
|
this._endpoint = config.endpoint;
|
|
129
130
|
this._appEndpoint = this.getEndpoint(
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { createInstance, Types } from "@amplitude/analytics-node";
|
|
3
|
+
import { getUserAgent, MCP_SERVER_VERSION } from "./info.js";
|
|
4
|
+
import { requestBearerClaims, getClaim, firstClaim } from "./jwt.js";
|
|
5
|
+
const ANALYTICS_API_KEY_ENV = "MCP_SERVER_AMPLITUDE_API_KEY";
|
|
6
|
+
const ANALYTICS_SOURCE = "MCP";
|
|
7
|
+
const FLUSH_TIMEOUT_MS = 5e3;
|
|
8
|
+
const AnalyticsEvent = {
|
|
9
|
+
SERVER_INITIALIZED: "Server Initialized",
|
|
10
|
+
SESSION_STARTED: "Session Started",
|
|
11
|
+
SESSION_ENDED: "Session Ended",
|
|
12
|
+
TOOL_CALLED: "Tool Called",
|
|
13
|
+
TOOLS_LISTED: "Tools Listed"
|
|
14
|
+
};
|
|
15
|
+
let amplitude;
|
|
16
|
+
const processDeviceId = randomUUID();
|
|
17
|
+
function analyticsIdFromEmail(email) {
|
|
18
|
+
return sha256(email.trim().toLowerCase());
|
|
19
|
+
}
|
|
20
|
+
function analyticsIdFromUserId(integration, userId) {
|
|
21
|
+
return sha256(`${integration}:${userId.trim()}`);
|
|
22
|
+
}
|
|
23
|
+
function sha256(value) {
|
|
24
|
+
return createHash("sha256").update(value).digest("hex");
|
|
25
|
+
}
|
|
26
|
+
function initAnalytics(env = process.env) {
|
|
27
|
+
if (amplitude) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
const apiKey = env[ANALYTICS_API_KEY_ENV]?.trim();
|
|
31
|
+
if (!apiKey) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const instance = createInstance();
|
|
36
|
+
instance.init(apiKey, {
|
|
37
|
+
// The SDK must never write to the MCP process's stdout/stderr on our
|
|
38
|
+
// behalf; failures are swallowed by design.
|
|
39
|
+
logLevel: Types.LogLevel.None
|
|
40
|
+
});
|
|
41
|
+
amplitude = instance;
|
|
42
|
+
return true;
|
|
43
|
+
} catch {
|
|
44
|
+
amplitude = void 0;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function resolveClientIdentity(client) {
|
|
49
|
+
const {
|
|
50
|
+
appName,
|
|
51
|
+
userId: userIdPaths,
|
|
52
|
+
organizationId,
|
|
53
|
+
tokenHeader
|
|
54
|
+
} = client.analytics ?? {};
|
|
55
|
+
const claims = requestBearerClaims(tokenHeader);
|
|
56
|
+
const email = getClaim(claims, "email");
|
|
57
|
+
const userId = email ? void 0 : firstClaim(claims, userIdPaths);
|
|
58
|
+
return {
|
|
59
|
+
analytics_id: email ? analyticsIdFromEmail(email) : userId ? analyticsIdFromUserId(client.capabilityPrefix, userId) : void 0,
|
|
60
|
+
organization: firstClaim(claims, organizationId),
|
|
61
|
+
app_name: appName?.trim() || void 0
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function resolveSessionIdentity(clients) {
|
|
65
|
+
let fallback = {};
|
|
66
|
+
for (const client of clients) {
|
|
67
|
+
const resolved = resolveClientIdentity(client);
|
|
68
|
+
if (resolved.analytics_id || resolved.organization) {
|
|
69
|
+
return resolved;
|
|
70
|
+
}
|
|
71
|
+
if (!fallback.app_name && resolved.app_name) {
|
|
72
|
+
fallback = resolved;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return fallback;
|
|
76
|
+
}
|
|
77
|
+
function mcpClientProperties(identity) {
|
|
78
|
+
return {
|
|
79
|
+
mcp_client_name: identity.name ?? null,
|
|
80
|
+
mcp_client_version: identity.version ?? null,
|
|
81
|
+
protocol_version: identity.protocolVersion ?? null
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function isToolsListRequest(message) {
|
|
85
|
+
if (Array.isArray(message)) {
|
|
86
|
+
return message.some((entry) => isToolsListRequest(entry));
|
|
87
|
+
}
|
|
88
|
+
return typeof message === "object" && message !== null && message.method === "tools/list";
|
|
89
|
+
}
|
|
90
|
+
function trackEvent(eventType, identity, properties, context = {}) {
|
|
91
|
+
if (!amplitude) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const eventProperties = stripUndefined({
|
|
96
|
+
app_name: identity.app_name,
|
|
97
|
+
organization: identity.organization,
|
|
98
|
+
analytics_id: identity.analytics_id,
|
|
99
|
+
source: ANALYTICS_SOURCE,
|
|
100
|
+
user_agent: context.userAgent ?? getUserAgent(),
|
|
101
|
+
...properties
|
|
102
|
+
});
|
|
103
|
+
amplitude.track(eventType, eventProperties, {
|
|
104
|
+
user_id: identity.analytics_id,
|
|
105
|
+
// A session-scoped device id lets a session's anonymous and identified
|
|
106
|
+
// events resolve to the same Amplitude user without ever sharing a
|
|
107
|
+
// device id between two real users.
|
|
108
|
+
device_id: context.sessionId ?? (identity.analytics_id ? void 0 : processDeviceId),
|
|
109
|
+
session_id: context.sessionStartedAt,
|
|
110
|
+
time: Date.now(),
|
|
111
|
+
insert_id: randomUUID(),
|
|
112
|
+
app_version: MCP_SERVER_VERSION
|
|
113
|
+
});
|
|
114
|
+
} catch {
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
let flushing;
|
|
118
|
+
let flushAgain = false;
|
|
119
|
+
function flushAnalytics() {
|
|
120
|
+
if (!amplitude) {
|
|
121
|
+
return Promise.resolve();
|
|
122
|
+
}
|
|
123
|
+
if (flushing) {
|
|
124
|
+
flushAgain = true;
|
|
125
|
+
return flushing;
|
|
126
|
+
}
|
|
127
|
+
flushing = (async () => {
|
|
128
|
+
do {
|
|
129
|
+
flushAgain = false;
|
|
130
|
+
await flushOnce();
|
|
131
|
+
} while (flushAgain);
|
|
132
|
+
flushing = void 0;
|
|
133
|
+
})();
|
|
134
|
+
return flushing;
|
|
135
|
+
}
|
|
136
|
+
async function flushOnce() {
|
|
137
|
+
let timer;
|
|
138
|
+
try {
|
|
139
|
+
await Promise.race([
|
|
140
|
+
amplitude?.flush().promise,
|
|
141
|
+
new Promise((resolve) => {
|
|
142
|
+
timer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
|
|
143
|
+
timer.unref?.();
|
|
144
|
+
})
|
|
145
|
+
]);
|
|
146
|
+
} catch {
|
|
147
|
+
} finally {
|
|
148
|
+
if (timer) clearTimeout(timer);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function trackToolCalled(outcome) {
|
|
152
|
+
if (!amplitude) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
outcome.session?.recordToolCall();
|
|
157
|
+
trackEvent(
|
|
158
|
+
AnalyticsEvent.TOOL_CALLED,
|
|
159
|
+
resolveClientIdentity(outcome.client),
|
|
160
|
+
{
|
|
161
|
+
session_id: outcome.session?.sessionId ?? null,
|
|
162
|
+
tool_name: outcome.toolName,
|
|
163
|
+
integration: outcome.client.capabilityPrefix,
|
|
164
|
+
success: outcome.success,
|
|
165
|
+
duration_ms: outcome.durationMs,
|
|
166
|
+
error_type: outcome.errorType,
|
|
167
|
+
...mcpClientProperties(outcome.mcpClient)
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
sessionId: outcome.session?.sessionId,
|
|
171
|
+
sessionStartedAt: outcome.session?.startedAt
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
} catch {
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function trackToolsListed(server) {
|
|
178
|
+
if (!amplitude) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const session = server.getAnalyticsSession();
|
|
183
|
+
trackEvent(
|
|
184
|
+
AnalyticsEvent.TOOLS_LISTED,
|
|
185
|
+
resolveSessionIdentity(server.getClients()),
|
|
186
|
+
{
|
|
187
|
+
session_id: session?.sessionId ?? null,
|
|
188
|
+
...mcpClientProperties(server.getMcpClientIdentity())
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
sessionId: session?.sessionId,
|
|
192
|
+
sessionStartedAt: session?.startedAt
|
|
193
|
+
}
|
|
194
|
+
);
|
|
195
|
+
} catch {
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function errorTypeOf(error) {
|
|
199
|
+
if (error instanceof Error) {
|
|
200
|
+
return error.constructor?.name || error.name || "Error";
|
|
201
|
+
}
|
|
202
|
+
return "UnknownError";
|
|
203
|
+
}
|
|
204
|
+
class AnalyticsSession {
|
|
205
|
+
sessionId;
|
|
206
|
+
startedAt = Date.now();
|
|
207
|
+
transport;
|
|
208
|
+
server;
|
|
209
|
+
integrations;
|
|
210
|
+
identity = {};
|
|
211
|
+
userAgent;
|
|
212
|
+
toolCallCount = 0;
|
|
213
|
+
started = false;
|
|
214
|
+
ended = false;
|
|
215
|
+
constructor(options) {
|
|
216
|
+
this.sessionId = options.sessionId;
|
|
217
|
+
this.transport = options.transport;
|
|
218
|
+
this.server = options.server;
|
|
219
|
+
this.integrations = options.integrations;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Called once the `initialize` request has been applied to the server, i.e.
|
|
223
|
+
* with the client identity known and inside the request context that
|
|
224
|
+
* carries the caller's credential. Emits `Session Started` then
|
|
225
|
+
* `Server Initialized`. Subsequent calls are ignored.
|
|
226
|
+
*/
|
|
227
|
+
onInitialized() {
|
|
228
|
+
if (this.started || !amplitude) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
this.started = true;
|
|
232
|
+
try {
|
|
233
|
+
const mcpClient = this.server.getMcpClientIdentity();
|
|
234
|
+
const clients = this.server.getClients();
|
|
235
|
+
this.identity = resolveSessionIdentity(clients);
|
|
236
|
+
this.userAgent = getUserAgent();
|
|
237
|
+
const configured = clients.filter((client) => isConfiguredWithAuth(client)).map((client) => client.capabilityPrefix);
|
|
238
|
+
const notConfigured = this.integrations.filter(
|
|
239
|
+
(integration) => !configured.includes(integration)
|
|
240
|
+
);
|
|
241
|
+
trackEvent(
|
|
242
|
+
AnalyticsEvent.SESSION_STARTED,
|
|
243
|
+
this.identity,
|
|
244
|
+
{
|
|
245
|
+
session_id: this.sessionId,
|
|
246
|
+
transport: this.transport,
|
|
247
|
+
...mcpClientProperties(mcpClient),
|
|
248
|
+
enabled_toolsets: this.server.getEnabledToolsets() ?? null,
|
|
249
|
+
enabled_integrations: this.integrations,
|
|
250
|
+
configured_integrations: configured,
|
|
251
|
+
not_configured_integrations: notConfigured
|
|
252
|
+
},
|
|
253
|
+
this.context()
|
|
254
|
+
);
|
|
255
|
+
trackEvent(
|
|
256
|
+
AnalyticsEvent.SERVER_INITIALIZED,
|
|
257
|
+
this.identity,
|
|
258
|
+
{
|
|
259
|
+
transport: this.transport,
|
|
260
|
+
...mcpClientProperties(mcpClient),
|
|
261
|
+
server_version: MCP_SERVER_VERSION
|
|
262
|
+
},
|
|
263
|
+
this.context()
|
|
264
|
+
);
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
recordToolCall() {
|
|
269
|
+
this.toolCallCount++;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Emit `Session Ended` and kick off a flush so the event is not stranded in
|
|
273
|
+
* the SDK's buffer when the session's transport goes away. No-op for a
|
|
274
|
+
* session that never completed `initialize`, and idempotent.
|
|
275
|
+
*/
|
|
276
|
+
end(reason) {
|
|
277
|
+
if (!this.started || this.ended || !amplitude) {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
this.ended = true;
|
|
281
|
+
try {
|
|
282
|
+
trackEvent(
|
|
283
|
+
AnalyticsEvent.SESSION_ENDED,
|
|
284
|
+
this.identity,
|
|
285
|
+
{
|
|
286
|
+
session_id: this.sessionId,
|
|
287
|
+
duration_ms: Date.now() - this.startedAt,
|
|
288
|
+
tool_call_count: this.toolCallCount,
|
|
289
|
+
end_reason: reason
|
|
290
|
+
},
|
|
291
|
+
this.context()
|
|
292
|
+
);
|
|
293
|
+
} catch {
|
|
294
|
+
}
|
|
295
|
+
void flushAnalytics();
|
|
296
|
+
}
|
|
297
|
+
context() {
|
|
298
|
+
return {
|
|
299
|
+
sessionId: this.sessionId,
|
|
300
|
+
sessionStartedAt: this.startedAt,
|
|
301
|
+
userAgent: this.userAgent
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function createAnalyticsSession(options) {
|
|
306
|
+
return amplitude ? new AnalyticsSession(options) : void 0;
|
|
307
|
+
}
|
|
308
|
+
function isConfiguredWithAuth(client) {
|
|
309
|
+
try {
|
|
310
|
+
if (!client.isConfigured()) {
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
return client.getAuthToken ? client.getAuthToken() !== null : true;
|
|
314
|
+
} catch {
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function stripUndefined(record) {
|
|
319
|
+
return Object.fromEntries(
|
|
320
|
+
Object.entries(record).filter(([, value]) => value !== void 0)
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
export {
|
|
324
|
+
ANALYTICS_API_KEY_ENV,
|
|
325
|
+
ANALYTICS_SOURCE,
|
|
326
|
+
AnalyticsEvent,
|
|
327
|
+
AnalyticsSession,
|
|
328
|
+
analyticsIdFromEmail,
|
|
329
|
+
analyticsIdFromUserId,
|
|
330
|
+
createAnalyticsSession,
|
|
331
|
+
errorTypeOf,
|
|
332
|
+
flushAnalytics,
|
|
333
|
+
initAnalytics,
|
|
334
|
+
isToolsListRequest,
|
|
335
|
+
mcpClientProperties,
|
|
336
|
+
resolveClientIdentity,
|
|
337
|
+
resolveSessionIdentity,
|
|
338
|
+
trackEvent,
|
|
339
|
+
trackToolCalled,
|
|
340
|
+
trackToolsListed
|
|
341
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getRequestHeader } from "./request-context.js";
|
|
2
|
+
function decodeJwtClaims(token) {
|
|
3
|
+
const segments = token?.trim().split(".") ?? [];
|
|
4
|
+
if (segments.length !== 3 || !segments[1]) {
|
|
5
|
+
return void 0;
|
|
6
|
+
}
|
|
7
|
+
try {
|
|
8
|
+
const parsed = JSON.parse(
|
|
9
|
+
Buffer.from(segments[1], "base64url").toString("utf8")
|
|
10
|
+
);
|
|
11
|
+
return isRecord(parsed) ? parsed : void 0;
|
|
12
|
+
} catch {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const AUTHORIZATION_HEADER = "Authorization";
|
|
17
|
+
function requestBearerClaims(tokenHeader) {
|
|
18
|
+
for (const header of candidateHeaders(tokenHeader)) {
|
|
19
|
+
const claims = decodeJwtClaims(readRequestToken(header));
|
|
20
|
+
if (claims) {
|
|
21
|
+
return claims;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
26
|
+
function candidateHeaders(tokenHeader) {
|
|
27
|
+
const declared = tokenHeader?.trim();
|
|
28
|
+
if (!declared || declared.toLowerCase() === AUTHORIZATION_HEADER.toLowerCase()) {
|
|
29
|
+
return [AUTHORIZATION_HEADER];
|
|
30
|
+
}
|
|
31
|
+
return [declared, AUTHORIZATION_HEADER];
|
|
32
|
+
}
|
|
33
|
+
function readRequestToken(name) {
|
|
34
|
+
const header = getRequestHeader(name);
|
|
35
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
36
|
+
return value?.replace(/^Bearer\s+/i, "");
|
|
37
|
+
}
|
|
38
|
+
function getClaim(claims, path) {
|
|
39
|
+
const segments = path.split(".");
|
|
40
|
+
const leaf = segments.pop();
|
|
41
|
+
let node = claims;
|
|
42
|
+
for (const segment of segments) {
|
|
43
|
+
node = isRecord(node) ? node[segment] : void 0;
|
|
44
|
+
}
|
|
45
|
+
if (!isRecord(node)) {
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
const direct = asClaimString(node[leaf]);
|
|
49
|
+
if (direct) {
|
|
50
|
+
return direct;
|
|
51
|
+
}
|
|
52
|
+
const namespaced = Object.entries(node).find(
|
|
53
|
+
([key]) => key.endsWith(`/${leaf}`)
|
|
54
|
+
);
|
|
55
|
+
return asClaimString(namespaced?.[1]);
|
|
56
|
+
}
|
|
57
|
+
function firstClaim(claims, paths) {
|
|
58
|
+
for (const path of paths ?? []) {
|
|
59
|
+
const value = getClaim(claims, path);
|
|
60
|
+
if (value) {
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return void 0;
|
|
65
|
+
}
|
|
66
|
+
function isRecord(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
68
|
+
}
|
|
69
|
+
function asClaimString(value) {
|
|
70
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
71
|
+
return String(value);
|
|
72
|
+
}
|
|
73
|
+
if (typeof value === "string" && value.trim()) {
|
|
74
|
+
return value.trim();
|
|
75
|
+
}
|
|
76
|
+
return void 0;
|
|
77
|
+
}
|
|
78
|
+
export {
|
|
79
|
+
decodeJwtClaims,
|
|
80
|
+
firstClaim,
|
|
81
|
+
getClaim,
|
|
82
|
+
requestBearerClaims
|
|
83
|
+
};
|