@posthog/mcp 0.7.0 → 0.9.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.
Files changed (84) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +51 -0
  3. package/dist/extensions/capture.d.ts.map +1 -1
  4. package/dist/extensions/capture.js +1 -0
  5. package/dist/extensions/capture.mjs +1 -0
  6. package/dist/extensions/compatibility.d.ts.map +1 -1
  7. package/dist/extensions/constants.d.ts +2 -0
  8. package/dist/extensions/constants.d.ts.map +1 -1
  9. package/dist/extensions/constants.js +2 -0
  10. package/dist/extensions/constants.mjs +2 -0
  11. package/dist/extensions/context-parameters.d.ts.map +1 -1
  12. package/dist/extensions/conversation-id.d.ts.map +1 -1
  13. package/dist/extensions/event-types.d.ts.map +1 -1
  14. package/dist/extensions/exceptions.d.ts.map +1 -1
  15. package/dist/extensions/ids.d.ts.map +1 -1
  16. package/dist/extensions/instrument-highlevel.d.ts.map +1 -1
  17. package/dist/extensions/instrument-lowlevel.d.ts.map +1 -1
  18. package/dist/extensions/instrumentation.d.ts.map +1 -1
  19. package/dist/extensions/instrumentation.js +39 -3
  20. package/dist/extensions/instrumentation.mjs +41 -5
  21. package/dist/extensions/intent.d.ts.map +1 -1
  22. package/dist/extensions/internal.d.ts.map +1 -1
  23. package/dist/extensions/logger.d.ts.map +1 -1
  24. package/dist/extensions/mcp-payloads.d.ts.map +1 -1
  25. package/dist/extensions/mcp-sdk-compat.d.ts.map +1 -1
  26. package/dist/extensions/posthog-events.d.ts.map +1 -1
  27. package/dist/extensions/posthog-events.js +6 -0
  28. package/dist/extensions/posthog-events.mjs +6 -0
  29. package/dist/extensions/posthog-mcp.d.ts.map +1 -1
  30. package/dist/extensions/posthog-mcp.js +2 -0
  31. package/dist/extensions/posthog-mcp.mjs +2 -0
  32. package/dist/extensions/sanitization.d.ts.map +1 -1
  33. package/dist/extensions/session-token.d.ts +46 -0
  34. package/dist/extensions/session-token.d.ts.map +1 -0
  35. package/dist/extensions/session-token.js +122 -0
  36. package/dist/extensions/session-token.mjs +76 -0
  37. package/dist/extensions/session.d.ts +5 -4
  38. package/dist/extensions/session.d.ts.map +1 -1
  39. package/dist/extensions/session.js +25 -33
  40. package/dist/extensions/session.mjs +22 -27
  41. package/dist/extensions/sink.d.ts.map +1 -1
  42. package/dist/extensions/tools.d.ts.map +1 -1
  43. package/dist/extensions/tracing-helpers.d.ts.map +1 -1
  44. package/dist/extensions/truncation.d.ts.map +1 -1
  45. package/dist/extensions/truncation.js +1 -0
  46. package/dist/extensions/truncation.mjs +1 -0
  47. package/dist/index.d.ts +3 -2
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +15 -2
  50. package/dist/index.mjs +2 -1
  51. package/dist/types.d.ts +32 -2
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/dist/version.mjs +1 -1
  56. package/package.json +3 -3
  57. package/src/extensions/capture.ts +11 -3
  58. package/src/extensions/compatibility.ts +4 -3
  59. package/src/extensions/constants.ts +6 -3
  60. package/src/extensions/context-parameters.ts +4 -3
  61. package/src/extensions/conversation-id.ts +4 -3
  62. package/src/extensions/event-types.ts +4 -3
  63. package/src/extensions/exceptions.ts +4 -3
  64. package/src/extensions/ids.ts +4 -3
  65. package/src/extensions/instrument-highlevel.ts +4 -3
  66. package/src/extensions/instrument-lowlevel.ts +4 -3
  67. package/src/extensions/instrumentation.ts +85 -9
  68. package/src/extensions/intent.ts +4 -3
  69. package/src/extensions/internal.ts +4 -3
  70. package/src/extensions/logger.ts +4 -3
  71. package/src/extensions/mcp-payloads.ts +4 -3
  72. package/src/extensions/mcp-sdk-compat.ts +4 -3
  73. package/src/extensions/posthog-events.ts +19 -3
  74. package/src/extensions/posthog-mcp.ts +2 -0
  75. package/src/extensions/sanitization.ts +4 -3
  76. package/src/extensions/session-token.ts +168 -0
  77. package/src/extensions/session.ts +42 -40
  78. package/src/extensions/sink.ts +4 -3
  79. package/src/extensions/tools.ts +4 -3
  80. package/src/extensions/tracing-helpers.ts +4 -3
  81. package/src/extensions/truncation.ts +5 -3
  82. package/src/index.ts +14 -4
  83. package/src/types.ts +38 -5
  84. package/src/version.ts +1 -1
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Self-encoded session tokens for stateless / multi-pod MCP servers.
3
+ *
4
+ * A stateless server keeps nothing between requests, so every request starts a
5
+ * new session and the client name/version (only sent at `initialize`) is lost.
6
+ * The one value clients replay on every request is the `Mcp-Session-Id` header.
7
+ * So at `initialize` we mint that header as a token carrying the session id and
8
+ * client identity — any pod can read them back from the header alone.
9
+ *
10
+ * The token is unsigned: it holds only what the client already self-reports.
11
+ */
12
+
13
+ export const MCP_SESSION_HEADER = 'mcp-session-id'
14
+
15
+ /** What a session token carries. */
16
+ export interface SessionTokenPayload {
17
+ /** PostHog session id (`ses_…`) → `$session_id`. */
18
+ sessionId: string
19
+ /** MCP client name → `$mcp_client_name`. */
20
+ clientName?: string
21
+ /** MCP client version → `$mcp_client_version`. */
22
+ clientVersion?: string
23
+ }
24
+
25
+ // On the wire the token is base64url(JSON) with shortened keys to keep the
26
+ // header small: sid = sessionId, cn = clientName, cv = clientVersion.
27
+ const MAX_TOKEN_LENGTH = 4096
28
+ const MAX_SESSION_ID_LENGTH = 128
29
+ const MAX_CLIENT_FIELD_LENGTH = 200
30
+
31
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+={0,2}$/
32
+
33
+ /**
34
+ * Encodes a session token for the `Mcp-Session-Id` response header. Also
35
+ * exported for SSE servers, which flush headers before handlers run and so
36
+ * must set the header themselves at the HTTP layer.
37
+ */
38
+ export function encodeSessionId(payload: SessionTokenPayload): string {
39
+ if (!payload || typeof payload.sessionId !== 'string' || payload.sessionId.length === 0) {
40
+ throw new Error('encodeSessionId requires a non-empty `sessionId` (use newSessionId())')
41
+ }
42
+ const wire: Record<string, string> = { sid: payload.sessionId }
43
+ if (typeof payload.clientName === 'string' && payload.clientName.length > 0) {
44
+ wire.cn = payload.clientName.slice(0, MAX_CLIENT_FIELD_LENGTH)
45
+ }
46
+ if (typeof payload.clientVersion === 'string' && payload.clientVersion.length > 0) {
47
+ wire.cv = payload.clientVersion.slice(0, MAX_CLIENT_FIELD_LENGTH)
48
+ }
49
+ return utf8ToBase64Url(JSON.stringify(wire))
50
+ }
51
+
52
+ /**
53
+ * Decodes an `Mcp-Session-Id` value into a token payload. Returns `null` for
54
+ * anything that isn't one of our tokens (transport UUIDs, JWTs, garbage) and
55
+ * never throws.
56
+ */
57
+ export function decodeSessionId(value: unknown): SessionTokenPayload | null {
58
+ if (typeof value !== 'string' || value.length === 0 || value.length > MAX_TOKEN_LENGTH) {
59
+ return null
60
+ }
61
+ // JWTs carry dots; UUIDs pass this check but fail JSON.parse below.
62
+ if (!BASE64URL_PATTERN.test(value)) {
63
+ return null
64
+ }
65
+ let parsed: unknown
66
+ try {
67
+ parsed = JSON.parse(base64UrlToUtf8(value))
68
+ } catch {
69
+ return null
70
+ }
71
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
72
+ return null
73
+ }
74
+ const wire = parsed as Record<string, unknown>
75
+ if (typeof wire.sid !== 'string' || wire.sid.length === 0 || wire.sid.length > MAX_SESSION_ID_LENGTH) {
76
+ return null
77
+ }
78
+ const payload: SessionTokenPayload = { sessionId: wire.sid }
79
+ // A bad cn/cv just means no client info — it does not reject the token.
80
+ if (typeof wire.cn === 'string' && wire.cn.length > 0) {
81
+ payload.clientName = wire.cn.slice(0, MAX_CLIENT_FIELD_LENGTH)
82
+ }
83
+ if (typeof wire.cv === 'string' && wire.cv.length > 0) {
84
+ payload.clientVersion = wire.cv.slice(0, MAX_CLIENT_FIELD_LENGTH)
85
+ }
86
+ return payload
87
+ }
88
+
89
+ /**
90
+ * Reads the `mcp-session-id` header off `extra.requestInfo.headers`. The SDK
91
+ * transports lowercase header keys; the fallback scan covers hand-built extras.
92
+ */
93
+ export function readMcpSessionHeader(headers: unknown): string | undefined {
94
+ if (!headers || typeof headers !== 'object') {
95
+ return undefined
96
+ }
97
+ const record = headers as Record<string, unknown>
98
+ let value = record[MCP_SESSION_HEADER]
99
+ if (value === undefined) {
100
+ const key = Object.keys(record).find((k) => k.toLowerCase() === MCP_SESSION_HEADER)
101
+ value = key === undefined ? undefined : record[key]
102
+ }
103
+ const first = Array.isArray(value) ? value[0] : value
104
+ if (typeof first !== 'string') {
105
+ return undefined
106
+ }
107
+ const trimmed = first.trim()
108
+ return trimmed.length > 0 ? trimmed : undefined
109
+ }
110
+
111
+ /**
112
+ * Puts a minted token on the transport so it goes out as the `Mcp-Session-Id`
113
+ * response header. The Node transport's `sessionId` is a getter backed by an
114
+ * inner web-standard transport, so verify the write by reading back and fall
115
+ * back to writing the inner one. Returns whether the write stuck; never throws.
116
+ */
117
+ export function writeSessionIdToTransport(transport: unknown, token: string): boolean {
118
+ if (!transport || typeof transport !== 'object') {
119
+ return false
120
+ }
121
+ const outer = transport as { sessionId?: string; _webStandardTransport?: unknown }
122
+ try {
123
+ outer.sessionId = token
124
+ } catch {
125
+ // getter-only wrapper — try the inner transport below
126
+ }
127
+ if (outer.sessionId === token) {
128
+ return true
129
+ }
130
+ const inner = outer._webStandardTransport
131
+ if (inner && typeof inner === 'object') {
132
+ try {
133
+ ;(inner as { sessionId?: string }).sessionId = token
134
+ } catch {
135
+ // read-only inner transport — the final read-back decides
136
+ }
137
+ }
138
+ return outer.sessionId === token
139
+ }
140
+
141
+ // base64url without assuming Node: Buffer where available, TextEncoder/btoa on
142
+ // edge runtimes. Must survive non-ASCII client names.
143
+
144
+ function utf8ToBase64Url(input: string): string {
145
+ if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
146
+ return Buffer.from(input, 'utf8').toString('base64url')
147
+ }
148
+ const bytes = new TextEncoder().encode(input)
149
+ let binary = ''
150
+ for (let i = 0; i < bytes.length; i++) {
151
+ binary += String.fromCharCode(bytes[i])
152
+ }
153
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
154
+ }
155
+
156
+ function base64UrlToUtf8(input: string): string {
157
+ const normalized = input.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')
158
+ const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
159
+ if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
160
+ return Buffer.from(padded, 'base64').toString('utf8')
161
+ }
162
+ const binary = atob(padded)
163
+ const bytes = new Uint8Array(binary.length)
164
+ for (let i = 0; i < binary.length; i++) {
165
+ bytes[i] = binary.charCodeAt(i)
166
+ }
167
+ return new TextDecoder().decode(bytes)
168
+ }
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import { version } from '../version'
6
7
  import type {
@@ -13,6 +14,7 @@ import type {
13
14
  import { INACTIVITY_TIMEOUT_IN_MINUTES } from './constants'
14
15
  import { deterministicPrefixedId, newPrefixedId } from './ids'
15
16
  import { getServerTrackingData, setServerTrackingData } from './internal'
17
+ import { decodeSessionId, readMcpSessionHeader } from './session-token'
16
18
 
17
19
  export function newSessionId(): string {
18
20
  return newPrefixedId('ses')
@@ -27,58 +29,58 @@ export function deriveSessionIdFromMCPSession(mcpSessionId: string): string {
27
29
  }
28
30
 
29
31
  /**
30
- * Resolves the session id for a request, preferring the MCP protocol sessionId
31
- * over an SDK-generated one so a transport-supplied session wins.
32
+ * Resolves the session id for a request: from the replayed session token, from
33
+ * the transport's MCP session id, or — when the request carries nothing — from
34
+ * this instance's memory. Also saves the token's client name/version so events
35
+ * built later in the request can use them (see getSessionInfo).
32
36
  */
33
- export function getServerSessionId(server: MCPServerLike, extra?: CompatibleRequestHandlerExtra): string {
37
+ export function getSessionId(server: MCPServerLike, extra?: CompatibleRequestHandlerExtra): string {
34
38
  const data = getServerTrackingData(server)
35
-
36
39
  if (!data) {
37
40
  throw new Error('Server tracking data not found')
38
41
  }
39
42
 
40
- const mcpSessionId = extra?.sessionId
41
-
42
- if (mcpSessionId) {
43
- data.sessionId = deriveSessionIdFromMCPSession(mcpSessionId)
44
- data.lastMcpSessionId = mcpSessionId
43
+ // Our token rides the `mcp-session-id` request header, which stateless
44
+ // transports ignore — so read it ourselves.
45
+ const sessionHeader = readMcpSessionHeader(extra?.requestInfo?.headers)
46
+ const token = decodeSessionId(sessionHeader)
47
+
48
+ let sessionId: string
49
+ if (token) {
50
+ // Token we minted at `initialize` (see session-token.ts).
51
+ data.sessionSource = 'token'
52
+ data.sessionInfo.clientName = token.clientName
53
+ data.sessionInfo.clientVersion = token.clientVersion
54
+ sessionId = token.sessionId
55
+ } else if (extra?.sessionId) {
56
+ // Session id issued by a stateful transport: hash it so the same MCP
57
+ // session maps to the same SDK session across restarts.
45
58
  data.sessionSource = 'mcp'
46
- setServerTrackingData(server, data)
47
- setLastActivity(server)
48
- return data.sessionId
59
+ sessionId = deriveSessionIdFromMCPSession(extra.sessionId)
60
+ } else {
61
+ sessionId = getSessionIdFromMemory(data)
49
62
  }
50
63
 
51
- // Once a session has been MCP-derived, keep that id even if a later request
52
- // arrives without the MCP sessionId, so the session doesn't fragment.
53
- if (data.sessionSource === 'mcp' && data.lastMcpSessionId) {
54
- setLastActivity(server)
55
- return data.sessionId
56
- }
64
+ data.sessionId = sessionId
65
+ data.lastActivity = new Date()
66
+ setServerTrackingData(server, data)
67
+ return sessionId
68
+ }
57
69
 
58
- // SDK-generated sessions roll over after an inactivity timeout.
59
- const now = Date.now()
70
+ /**
71
+ * Nothing replayed on this request: keep the id we already have. Only
72
+ * generated sessions roll over on inactivity — token/MCP ids live as long as
73
+ * the client replays them, and regenerating one would split the session.
74
+ */
75
+ function getSessionIdFromMemory(data: MCPAnalyticsData): string {
60
76
  const timeoutMs = INACTIVITY_TIMEOUT_IN_MINUTES * 60 * 1000
61
- if (now - data.lastActivity.getTime() > timeoutMs) {
62
- data.sessionId = newSessionId()
63
- data.sessionSource = 'generated'
64
- setServerTrackingData(server, data)
77
+ const isStale = Date.now() - data.lastActivity.getTime() > timeoutMs
78
+ if (data.sessionSource === 'generated' && isStale) {
79
+ return newSessionId()
65
80
  }
66
- setLastActivity(server)
67
-
68
81
  return data.sessionId
69
82
  }
70
83
 
71
- export function setLastActivity(server: MCPServerLike): void {
72
- const data = getServerTrackingData(server)
73
-
74
- if (!data) {
75
- throw new Error('Server tracking data not found')
76
- }
77
-
78
- data.lastActivity = new Date()
79
- setServerTrackingData(server, data)
80
- }
81
-
82
84
  /**
83
85
  * Builds the session metadata stamped onto an event. The caller passes the
84
86
  * session id resolved for *this* request so identity attribution can't be
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import type { PostHog } from 'posthog-node'
6
7
  import { uuidv7 } from '@posthog/core'
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import { type CallToolResult, type ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
6
7
  import { log } from './logger'
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import type { CompatibleRequestHandlerExtra, MCPAnalyticsData, MCPRequestLike, McpEvent } from '../types'
6
7
  import { resolveEventProperties } from './internal'
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import type { ErrorProperties, Event, StackFrame, McpEvent } from '../types'
6
7
 
@@ -429,6 +430,7 @@ export function truncateEvent<T extends Event | McpEvent>(event: T): T {
429
430
  result.serverVersion = truncateString(result.serverVersion, MAX_METADATA_LENGTH)
430
431
  result.clientName = truncateString(result.clientName, MAX_METADATA_LENGTH)
431
432
  result.clientVersion = truncateString(result.clientVersion, MAX_METADATA_LENGTH)
433
+ result.errorType = truncateString(result.errorType, MAX_METADATA_LENGTH)
432
434
 
433
435
  // Error field limits — operate on the core `$exception_list` shape
434
436
  if (result.error != null && typeof result.error === 'object') {
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import type { PostHog } from 'posthog-node'
6
7
  import { isCompatibleServerType, isHighLevelServer } from './extensions/compatibility'
@@ -191,7 +192,16 @@ async function captureCustomEvent(lowLevelServer: MCPServerLike, eventData: Capt
191
192
  log(`Captured event "${eventData.event}" for session ${trackingData.sessionId}`)
192
193
  }
193
194
 
194
- export { deriveSessionIdFromMCPSession }
195
+ export { deriveSessionIdFromMCPSession, newSessionId }
196
+ // Session tokens for stateless / multi-pod servers. Minted and decoded
197
+ // automatically on JSON-mode StreamableHTTP; SSE servers set the header
198
+ // themselves with `encodeSessionId`.
199
+ export {
200
+ MCP_SESSION_HEADER,
201
+ decodeSessionId,
202
+ encodeSessionId,
203
+ type SessionTokenPayload,
204
+ } from './extensions/session-token'
195
205
  export {
196
206
  POSTHOG_MCP_ANALYTICS_SOURCE,
197
207
  PostHogMCPAnalyticsEvent,
package/src/types.ts CHANGED
@@ -1,6 +1,7 @@
1
- // Portions of this file are derived from MCPCat/mcpcat-typescript-sdk
2
- // Copyright (c) 2025 MCPcat
3
- // Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE
1
+ // Portions of this file are derived from agentcathq/agentcat-typescript-sdk
2
+ // (formerly MCPCat/mcpcat-typescript-sdk)
3
+ // Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat)
4
+ // Licensed under the MIT License: https://github.com/agentcathq/agentcat-typescript-sdk/blob/main/LICENSE
4
5
 
5
6
  import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
6
7
  import type { ErrorTracking } from '@posthog/core'
@@ -136,6 +137,13 @@ export interface Event {
136
137
  conversationId?: string
137
138
  duration?: number
138
139
  error?: ErrorProperties | null
140
+ /**
141
+ * Coarse failure category → `$mcp_error_type`. An explicit, low-cardinality
142
+ * label the host can supply (e.g. `validation`, `permission`, `timeout`).
143
+ * When omitted on an errored call, it falls back to the thrown error's type
144
+ * (the `$exception_list` entry's `type`).
145
+ */
146
+ errorType?: string
139
147
  eventId?: string
140
148
  eventType: MCPAnalyticsEventType
141
149
  groups?: Record<string, string>
@@ -172,9 +180,17 @@ export interface Event {
172
180
  /** A partially-built MCP event as it flows through the SDK before capture. */
173
181
  export type McpEvent = Partial<Event>
174
182
 
183
+ /** HTTP request info the SDK's Streamable HTTP transports attach per request. */
184
+ export interface CompatibleRequestInfoLike {
185
+ headers?: Record<string, string | string[] | undefined>
186
+ [key: string]: unknown
187
+ }
188
+
175
189
  export interface CompatibleRequestHandlerExtra {
176
190
  headers?: Record<string, string | string[]>
177
191
  sessionId?: string
192
+ /** Present on HTTP transports only — headers ride every request, unlike `clientInfo`. */
193
+ requestInfo?: CompatibleRequestInfoLike
178
194
  [key: string]: unknown
179
195
  }
180
196
 
@@ -192,9 +208,17 @@ export interface HighLevelMCPServerLike {
192
208
  tool?(name: string, description: string, paramsSchema: unknown, cb: ToolCallback): void
193
209
  }
194
210
 
211
+ /** The connected transport as exposed by the SDK's `Protocol.transport` getter. */
212
+ export interface CompatibleTransportLike {
213
+ sessionId?: string
214
+ [key: string]: unknown
215
+ }
216
+
195
217
  export interface MCPServerLike {
196
218
  _requestHandlers: Map<string, (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Promise<unknown>>
197
219
  _serverInfo?: ServerClientInfoLike
220
+ /** Optional so older SDKs (and bare test doubles) still validate. */
221
+ transport?: CompatibleTransportLike
198
222
  getClientVersion(): ServerClientInfoLike | undefined
199
223
  setRequestHandler(
200
224
  schema: unknown,
@@ -238,11 +262,11 @@ export interface MCPAnalyticsData {
238
262
  sink: McpEventSink | undefined
239
263
  identifiedSessions: IdentityCache
240
264
  lastActivity: Date
241
- lastMcpSessionId?: string
242
265
  options: MCPAnalyticsOptions
243
266
  sessionId: string
244
267
  sessionInfo: SessionInfo
245
- sessionSource: 'generated' | 'mcp'
268
+ /** `token` = recovered from a self-encoded `Mcp-Session-Id` token (see session-token.ts). */
269
+ sessionSource: 'generated' | 'mcp' | 'token'
246
270
  toolCategories: Map<string, string>
247
271
  toolDescriptions: Map<string, string>
248
272
  }
@@ -317,6 +341,13 @@ export interface ToolCallCaptureData extends McpCaptureCommon {
317
341
  * synthesized from the tool name.
318
342
  */
319
343
  error?: unknown
344
+ /**
345
+ * Coarse failure category → `$mcp_error_type` (e.g. `validation`,
346
+ * `permission`, `timeout`, `rate_limited`). A low-cardinality label that lets
347
+ * the dashboard break failures down by reason without joining to `$exception`.
348
+ * When omitted on an error, the SDK falls back to the thrown error's type.
349
+ */
350
+ errorType?: string
320
351
  }
321
352
 
322
353
  /** Payload for {@link PostHogMCP.captureInitialize}. Emits `$mcp_initialize`. */
@@ -350,6 +381,8 @@ export interface ToolsListCaptureData extends McpCaptureCommon {
350
381
  isError?: boolean
351
382
  /** The thrown value when `isError` is true → fans out an `$exception` sibling. */
352
383
  error?: unknown
384
+ /** Coarse failure category → `$mcp_error_type`. Falls back to the thrown error's type. */
385
+ errorType?: string
353
386
  }
354
387
 
355
388
  /** Options for {@link PostHogMCP.prepareToolList}. */
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '0.7.0'
1
+ export const version = '0.9.0'