Skip to content

Cache tool call params #646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SESSION_KEYS, getServerSpecificKey } from "./lib/constants";
import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "./lib/auth-types";
import { OAuthStateMachine } from "./lib/oauth-state-machine";
import { cacheToolOutputSchemas } from "./utils/schemaUtils";
import { saveToolParamsForCache } from "./utils/toolCache";
import React, {
Suspense,
useCallback,
Expand Down Expand Up @@ -688,6 +689,12 @@ const App = () => {
const callTool = async (name: string, params: Record<string, unknown>) => {
lastToolCallOriginTabRef.current = currentTabRef.current;

// Save tool parameters to cache before making the call
const tool = tools.find((t) => t.name === name);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Save the tool parameters to localStorage cache on execution.

if (tool && sseUrl) {
saveToolParamsForCache(sseUrl, name, tool, params);
}

try {
const response = await sendMCPRequest(
{
Expand Down Expand Up @@ -1020,6 +1027,7 @@ const App = () => {
clearError("resources");
readResource(uri);
}}
serverUrl={sseUrl}
/>
<ConsoleTab />
<PingTab
Expand Down
31 changes: 26 additions & 5 deletions client/src/components/ToolsTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useEffect, useState } from "react";
import ListPane from "./ListPane";
import JsonView from "./JsonView";
import ToolResults from "./ToolResults";
import { loadToolParamsFromCache } from "@/utils/toolCache";

const ToolsTab = ({
tools,
Expand All @@ -30,6 +31,7 @@ const ToolsTab = ({
nextCursor,
resourceContent,
onReadResource,
serverUrl,
}: {
tools: Tool[];
listTools: () => void;
Expand All @@ -42,24 +44,43 @@ const ToolsTab = ({
error: string | null;
resourceContent: Record<string, string>;
onReadResource?: (uri: string) => void;
serverUrl: string;
}) => {
const [params, setParams] = useState<Record<string, unknown>>({});
const [isToolRunning, setIsToolRunning] = useState(false);
const [isOutputSchemaExpanded, setIsOutputSchemaExpanded] = useState(false);

useEffect(() => {
const params = Object.entries(
selectedTool?.inputSchema.properties ?? [],
if (!selectedTool) {
setParams({});
return;
}

// Generate default parameters from schema
const defaultParams = Object.entries(
selectedTool.inputSchema.properties ?? [],
).map(([key, value]) => [
key,
generateDefaultValue(
value as JsonSchemaType,
key,
selectedTool?.inputSchema as JsonSchemaType,
selectedTool.inputSchema as JsonSchemaType,
),
]);
setParams(Object.fromEntries(params));
}, [selectedTool]);
const defaultParamsObj = Object.fromEntries(defaultParams);

// Fetch cached params from localStorage if they exist
const cachedParams = loadToolParamsFromCache(
serverUrl,
selectedTool.name,
selectedTool,
);

// Merge cached params with defaults, giving preference to cached values
const mergedParams = { ...defaultParamsObj, ...cachedParams };
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First load the empty default params, then load the cached ones if they exist.


setParams(mergedParams);
}, [selectedTool, serverUrl]);

return (
<TabsContent value="tools">
Expand Down
71 changes: 71 additions & 0 deletions client/src/utils/toolCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Tool } from "@modelcontextprotocol/sdk/types.js";

export interface CacheKey {
serverUrl: string;
toolName: string;
paramNames: string[];
}

export function generateCacheKey(
serverUrl: string,
toolName: string,
tool: Tool,
): string {
const paramNames = Object.keys(tool.inputSchema.properties ?? {}).sort();
const key = `tool_params_${btoa(`${serverUrl}_${toolName}_${JSON.stringify(paramNames)}`)}`;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ensures uniqueness in localStorage

return key;
}

export function saveToolParamsForCache(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We create a tool cache helper util that helps save and load things from localStorage

serverUrl: string,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can probably remove serverUrl. Lmk if that'd be better, but also down to just keep it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I can see advantages either way. Probably safer to start conservative, with the additional uniqueness of the server URL?

toolName: string,
tool: Tool,
params: Record<string, unknown>,
): void {
try {
const cacheKey = generateCacheKey(serverUrl, toolName, tool);
const cacheData = {
params,
timestamp: Date.now(),
toolName,
serverUrl,
};
localStorage.setItem(cacheKey, JSON.stringify(cacheData));
} catch (error) {
console.warn("Failed to save tool parameters to cache:", error);
}
}

export function loadToolParamsFromCache(
serverUrl: string,
toolName: string,
tool: Tool,
): Record<string, unknown> | null {
try {
const cacheKey = generateCacheKey(serverUrl, toolName, tool);
const cached = localStorage.getItem(cacheKey);

if (!cached) {
return null;
}

const cacheData = JSON.parse(cached);

// Validate cache data structure
if (!cacheData.params || !cacheData.timestamp) {
return null;
}

// Optional: Check if cache is too old (e.g., 30 days)
const maxAge = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds
if (Date.now() - cacheData.timestamp > maxAge) {
localStorage.removeItem(cacheKey);
return null;
}

return cacheData.params;
} catch (error) {
console.warn("Failed to load tool parameters from cache:", error);
return null;
}
}