Skip to content

Commit 64bc4b6

Browse files
msukkariclaude
andcommitted
refactor(web): move captureEvent error handling into captureEvent itself
captureEvent now wraps its body in try/catch so callers are guaranteed it won't throw. Removed all .catch() handlers from call sites in adapters.ts, server.ts, and apiHandler.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 5bfdd29 commit 64bc4b6

File tree

4 files changed

+30
-40
lines changed

4 files changed

+30
-40
lines changed

packages/web/src/features/mcp/server.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { captureEvent } from '@/lib/posthog';
66
import { isServiceError } from '@/lib/utils';
77
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
88
import { ChatVisibility } from '@sourcebot/db';
9-
import { createLogger, SOURCEBOT_VERSION } from '@sourcebot/shared';
9+
import { SOURCEBOT_VERSION } from '@sourcebot/shared';
1010
import _dedent from 'dedent';
1111
import { z } from 'zod';
1212
import { getConfiguredLanguageModelsInfo } from "../chat/utils.server";
@@ -24,7 +24,6 @@ import {
2424
} from '../tools';
2525

2626
const dedent = _dedent.withOptions({ alignValues: true });
27-
const logger = createLogger('mcp-server');
2827

2928
export async function createMcpServer(options?: { userId?: string }): Promise<McpServer> {
3029
const server = new McpServer({
@@ -64,9 +63,7 @@ export async function createMcpServer(options?: { userId?: string }): Promise<Mc
6463
toolName: 'list_language_models',
6564
source: 'sourcebot-mcp-server',
6665
success: true,
67-
}, { distinctId: options?.userId }).catch((error) => {
68-
logger.warn('Failed to capture tool_used event:', error);
69-
});
66+
}, { distinctId: options?.userId });
7067
return { content: [{ type: "text", text: JSON.stringify(models) }] };
7168
}
7269
);
@@ -115,9 +112,7 @@ export async function createMcpServer(options?: { userId?: string }): Promise<Mc
115112
toolName: 'ask_codebase',
116113
source: 'sourcebot-mcp-server',
117114
success: false,
118-
}, { distinctId: options?.userId }).catch((error) => {
119-
logger.warn('Failed to capture tool_used event:', error);
120-
});
115+
}, { distinctId: options?.userId });
121116
return {
122117
content: [{ type: "text", text: `Failed to ask codebase: ${result.message}` }],
123118
};
@@ -127,9 +122,7 @@ export async function createMcpServer(options?: { userId?: string }): Promise<Mc
127122
toolName: 'ask_codebase',
128123
source: 'sourcebot-mcp-server',
129124
success: true,
130-
}, { distinctId: options?.userId }).catch((error) => {
131-
logger.warn('Failed to capture tool_used event:', error);
132-
});
125+
}, { distinctId: options?.userId });
133126

134127
const formattedResponse = dedent`
135128
${result.answer}

packages/web/src/features/tools/adapters.ts

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
33
import { z } from "zod";
44
import { captureEvent } from "@/lib/posthog";
55
import { ToolContext, ToolDefinition } from "./types";
6-
import { logger } from "./logger";
76

87
export function toVercelAITool<TName extends string, TShape extends z.ZodRawShape, TMetadata>(
98
def: ToolDefinition<TName, TShape, TMetadata>,
@@ -25,9 +24,7 @@ export function toVercelAITool<TName extends string, TShape extends z.ZodRawShap
2524
toolName: def.name,
2625
source: context.source ?? 'unknown',
2726
success,
28-
}, { distinctId: context.userId }).catch((error) => {
29-
logger.warn(`Failed to capture tool_used event for ${def.name}:`, error);
30-
});
27+
}, { distinctId: context.userId });
3128
}
3229
},
3330
toModelOutput: ({ output }) => ({
@@ -70,9 +67,7 @@ export function registerMcpTool<TName extends string, TShape extends z.ZodRawSha
7067
toolName: def.name,
7168
source: context.source ?? 'unknown',
7269
success,
73-
}, { distinctId: context.userId }).catch((error) => {
74-
logger.warn(`Failed to capture tool_used event for ${def.name}:`, error);
75-
});
70+
}, { distinctId: context.userId });
7671
}
7772
},
7873
);

packages/web/src/lib/apiHandler.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,7 @@ export function apiHandler<H extends AnyHandler>(
4747
const source = request.headers.get('X-Sourcebot-Client-Source') ?? 'unknown';
4848

4949
// Fire and forget - don't await to avoid blocking the request
50-
captureEvent('api_request', { path, method, source }).catch(() => {
51-
// Silently ignore tracking errors
52-
});
50+
captureEvent('api_request', { path, method, source });
5351
}
5452

5553
// Call the original handler with all arguments

packages/web/src/lib/posthog.ts

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -88,24 +88,28 @@ export const createPostHogClient = async () => {
8888
}
8989

9090
export async function captureEvent<E extends PosthogEvent>(event: E, properties: PosthogEventMap[E], options?: { distinctId?: string }) {
91-
if (env.SOURCEBOT_TELEMETRY_DISABLED === 'true') {
92-
return;
93-
}
94-
95-
const distinctId = options?.distinctId ?? await tryGetPostHogDistinctId();
96-
const posthog = await createPostHogClient();
91+
try {
92+
if (env.SOURCEBOT_TELEMETRY_DISABLED === 'true') {
93+
return;
94+
}
9795

98-
const headersList = await headers();
99-
const host = headersList.get("host") ?? undefined;
100-
101-
posthog.capture({
102-
event,
103-
properties: {
104-
...properties,
105-
sourcebot_version: SOURCEBOT_VERSION,
106-
install_id: env.SOURCEBOT_INSTALL_ID,
107-
$host: host,
108-
},
109-
distinctId,
110-
});
96+
const distinctId = options?.distinctId ?? await tryGetPostHogDistinctId();
97+
const posthog = await createPostHogClient();
98+
99+
const headersList = await headers();
100+
const host = headersList.get("host") ?? undefined;
101+
102+
posthog.capture({
103+
event,
104+
properties: {
105+
...properties,
106+
sourcebot_version: SOURCEBOT_VERSION,
107+
install_id: env.SOURCEBOT_INSTALL_ID,
108+
$host: host,
109+
},
110+
distinctId,
111+
});
112+
} catch {
113+
// Telemetry should never break application functionality.
114+
}
111115
}

0 commit comments

Comments
 (0)