Skip to content

Commit 32cdc84

Browse files
committed
@W-20995739 - add MCP tool-level response token usage (responseCharCount)
1 parent fb0a14b commit 32cdc84

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

packages/mcp/src/sf-mcp-server.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,22 @@ export class SfMcpServer extends McpServer implements ToolMethodSignatures {
8888
};
8989
}
9090

91+
/**
92+
* Calculates the total character count from tool result content
93+
* Used for token usage
94+
* @param result - The CallToolResult from tool execution
95+
* @returns Total character count across all text content items
96+
*/
97+
private calculateResponseCharCount(result: CallToolResult): number {
98+
if (!result.content || !Array.isArray(result.content)) {
99+
return 0;
100+
}
101+
102+
return result.content
103+
.filter((item): item is { type: 'text'; text: string } => item.type === 'text')
104+
.reduce((sum, item) => sum + item.text.length, 0);
105+
}
106+
91107
public registerTool<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape>(
92108
name: string,
93109
config: {
@@ -141,6 +157,9 @@ export class SfMcpServer extends McpServer implements ToolMethodSignatures {
141157
this.logger.debug(`Tool ${name} completed in ${runtimeMs}ms`);
142158
if (result.isError) this.logger.debug(`Tool ${name} errored`);
143159

160+
// Calculate response character count for token usage
161+
const responseCharCount = this.calculateResponseCharCount(result);
162+
144163
this.telemetry?.sendEvent('TOOL_CALLED', {
145164
name,
146165
runtimeMs,
@@ -151,6 +170,7 @@ export class SfMcpServer extends McpServer implements ToolMethodSignatures {
151170
//
152171
// https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult
153172
isError: result.isError ?? false,
173+
responseCharCount: responseCharCount.toString(),
154174
});
155175

156176
return result;

0 commit comments

Comments
 (0)