|
1 | 1 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; |
| 2 | +import type { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'; |
2 | 3 | import type { z } from 'zod'; |
3 | 4 | import { createRequire } from 'module'; |
4 | 5 | import { whoAmI, type WhoAmI } from '@huggingface/hub'; |
@@ -54,19 +55,25 @@ import { |
54 | 55 | type DocFetchParams, |
55 | 56 | HF_JOBS_TOOL_CONFIG, |
56 | 57 | HfJobsTool, |
| 58 | + DYNAMIC_SPACE_TOOL_CONFIG, |
| 59 | + SpaceTool, |
| 60 | + type SpaceArgs, |
| 61 | + type InvokeResult, |
| 62 | + type ToolResult, |
57 | 63 | } from '@llmindset/hf-mcp'; |
58 | 64 |
|
59 | 65 | import type { ServerFactory, ServerFactoryResult } from './transport/base-transport.js'; |
60 | 66 | import type { McpApiClient } from './utils/mcp-api-client.js'; |
61 | 67 | import type { WebServer } from './web-server.js'; |
62 | 68 | import { logger } from './utils/logger.js'; |
63 | | -import { logSearchQuery, logPromptQuery } from './utils/query-logger.js'; |
| 69 | +import { logSearchQuery, logPromptQuery, logGradioEvent } from './utils/query-logger.js'; |
64 | 70 | import { DEFAULT_SPACE_TOOLS, type AppSettings } from '../shared/settings.js'; |
65 | 71 | import { extractAuthBouquetAndMix } from './utils/auth-utils.js'; |
66 | 72 | import { ToolSelectionStrategy, type ToolSelectionContext } from './utils/tool-selection-strategy.js'; |
67 | 73 | import { hasReadmeFlag } from '../shared/behavior-flags.js'; |
68 | 74 | import { registerCapabilities } from './utils/capability-utils.js'; |
69 | 75 | import { createGradioWidgetResourceConfig } from './resources/gradio-widget-resource.js'; |
| 76 | +import { applyResultPostProcessing, type GradioToolCallOptions } from './utils/gradio-tool-caller.js'; |
70 | 77 |
|
71 | 78 | // Fallback settings when API fails (enables all tools) |
72 | 79 | export const BOUQUET_FALLBACK: AppSettings = { |
@@ -176,6 +183,9 @@ export const createServerFactory = (_webServerInstance: WebServer, sharedApiClie |
176 | 183 | hfToken, |
177 | 184 | }; |
178 | 185 | const toolSelection = await toolSelectionStrategy.selectTools(toolSelectionContext); |
| 186 | + const rawNoImageHeader = headers?.['x-mcp-no-image-content']; |
| 187 | + const noImageContentHeaderEnabled = |
| 188 | + typeof rawNoImageHeader === 'string' && rawNoImageHeader.trim().toLowerCase() === 'true'; |
179 | 189 |
|
180 | 190 | // Always register all tools and store instances for dynamic control |
181 | 191 | const toolInstances: { [name: string]: Tool } = {}; |
@@ -686,6 +696,124 @@ export const createServerFactory = (_webServerInstance: WebServer, sharedApiClie |
686 | 696 | } |
687 | 697 | ); |
688 | 698 |
|
| 699 | + toolInstances[DYNAMIC_SPACE_TOOL_CONFIG.name] = server.tool( |
| 700 | + DYNAMIC_SPACE_TOOL_CONFIG.name, |
| 701 | + DYNAMIC_SPACE_TOOL_CONFIG.description, |
| 702 | + DYNAMIC_SPACE_TOOL_CONFIG.schema.shape, |
| 703 | + DYNAMIC_SPACE_TOOL_CONFIG.annotations, |
| 704 | + async (params: SpaceArgs, extra) => { |
| 705 | + // Check if invoke operation is disabled by gradio=none |
| 706 | + const { gradio } = extractAuthBouquetAndMix(headers); |
| 707 | + if (params.operation === 'invoke' && gradio === 'none') { |
| 708 | + const errorMessage = |
| 709 | + 'The invoke operation is disabled because gradio=none is set. ' + |
| 710 | + 'To use invoke, remove gradio=none from your headers or set gradio to a space ID. ' + |
| 711 | + 'You can still use operation=view_parameters to inspect the tool schema.'; |
| 712 | + return { |
| 713 | + content: [{ type: 'text', text: errorMessage }], |
| 714 | + isError: true, |
| 715 | + }; |
| 716 | + } |
| 717 | + |
| 718 | + const startTime = Date.now(); |
| 719 | + let success = false; |
| 720 | + |
| 721 | + try { |
| 722 | + const spaceTool = new SpaceTool(hfToken); |
| 723 | + const result = await spaceTool.execute(params, extra); |
| 724 | + |
| 725 | + // Check if this is an InvokeResult (has raw MCP content from invoke operation) |
| 726 | + if ('result' in result && result.result) { |
| 727 | + const invokeResult = result as InvokeResult; |
| 728 | + success = !invokeResult.isError; |
| 729 | + |
| 730 | + // Prepare post-processing options |
| 731 | + const stripImageContent = |
| 732 | + noImageContentHeaderEnabled || toolSelection.enabledToolIds.includes('NO_GRADIO_IMAGE_CONTENT'); |
| 733 | + const postProcessOptions: GradioToolCallOptions = { |
| 734 | + stripImageContent, |
| 735 | + toolName: DYNAMIC_SPACE_TOOL_CONFIG.name, |
| 736 | + outwardFacingName: DYNAMIC_SPACE_TOOL_CONFIG.name, |
| 737 | + sessionInfo, |
| 738 | + spaceName: params.space_name, |
| 739 | + }; |
| 740 | + |
| 741 | + // Apply unified post-processing (image filtering + OpenAI transforms) |
| 742 | + const processedResult = applyResultPostProcessing( |
| 743 | + invokeResult.result as typeof CallToolResultSchema._type, |
| 744 | + postProcessOptions |
| 745 | + ); |
| 746 | + |
| 747 | + // Prepend warnings if any |
| 748 | + const warningsContent = |
| 749 | + invokeResult.warnings.length > 0 |
| 750 | + ? [ |
| 751 | + { |
| 752 | + type: 'text' as const, |
| 753 | + text: |
| 754 | + (invokeResult.warnings.length === 1 ? 'Warning:\n' : 'Warnings:\n') + |
| 755 | + invokeResult.warnings.map((w) => `- ${w}`).join('\n') + |
| 756 | + '\n', |
| 757 | + }, |
| 758 | + ] |
| 759 | + : []; |
| 760 | + |
| 761 | + // Log Gradio event with timing metrics for invoke operation (like proxied tools) |
| 762 | + const endTime = Date.now(); |
| 763 | + const responseContent = [...warningsContent, ...(processedResult.content as unknown[])]; |
| 764 | + logGradioEvent(params.space_name || 'unknown-space', sessionInfo?.clientSessionId || 'unknown', { |
| 765 | + durationMs: endTime - startTime, |
| 766 | + isAuthenticated: !!hfToken, |
| 767 | + clientName: sessionInfo?.clientInfo?.name, |
| 768 | + clientVersion: sessionInfo?.clientInfo?.version, |
| 769 | + success, |
| 770 | + error: invokeResult.isError ? 'Tool returned isError=true' : undefined, |
| 771 | + responseSizeBytes: JSON.stringify(responseContent).length, |
| 772 | + isDynamic: true, // Mark as dynamic invocation (vs proxied gr_* tool) |
| 773 | + }); |
| 774 | + |
| 775 | + return { |
| 776 | + content: responseContent, |
| 777 | + ...(invokeResult.isError && { isError: true }), |
| 778 | + } as typeof CallToolResultSchema._type; |
| 779 | + } |
| 780 | + |
| 781 | + // For view_parameters and errors - return formatted text |
| 782 | + const toolResult = result as ToolResult; |
| 783 | + success = !toolResult.isError; |
| 784 | + |
| 785 | + const loggedOperation = params.operation ?? 'no-operation'; |
| 786 | + logSearchQuery(DYNAMIC_SPACE_TOOL_CONFIG.name, loggedOperation, params, { |
| 787 | + ...getLoggingOptions(), |
| 788 | + totalResults: toolResult.totalResults, |
| 789 | + resultsShared: toolResult.resultsShared, |
| 790 | + responseCharCount: toolResult.formatted.length, |
| 791 | + }); |
| 792 | + |
| 793 | + return { |
| 794 | + content: [{ type: 'text', text: toolResult.formatted }], |
| 795 | + ...(toolResult.isError && { isError: true }), |
| 796 | + }; |
| 797 | + } catch (err) { |
| 798 | + // Log error for invoke operation |
| 799 | + if (params.operation === 'invoke') { |
| 800 | + const endTime = Date.now(); |
| 801 | + logGradioEvent(params.space_name || 'unknown-space', sessionInfo?.clientSessionId || 'unknown', { |
| 802 | + durationMs: endTime - startTime, |
| 803 | + isAuthenticated: !!hfToken, |
| 804 | + clientName: sessionInfo?.clientInfo?.name, |
| 805 | + clientVersion: sessionInfo?.clientInfo?.version, |
| 806 | + success: false, |
| 807 | + error: err, |
| 808 | + isDynamic: true, |
| 809 | + }); |
| 810 | + } |
| 811 | + |
| 812 | + throw err; |
| 813 | + } |
| 814 | + } |
| 815 | + ); |
| 816 | + |
689 | 817 | // Register Gradio widget resource for OpenAI MCP client (skybridge) |
690 | 818 | if (sessionInfo?.clientInfo?.name === 'openai-mcp') { |
691 | 819 | logger.debug('Registering Gradio widget resource for skybridge client'); |
|
0 commit comments