多层工具调用反射工具

一个简单的工具,用于在多层工具调用中反射服务器端工具调用,使模型能够正确调用客户端和服务器端工具。

  • by stanley2058
  • JavaScript
  • 本地部署
  • 更新于
在 GitHub 查看 stanley2058/local-reflect-mcp

使用说明

本地反映mcp

这是一个简单的工具,用于反映多层工具调用的服务器端工具调用。

如果你和我一样,有以下要求:

  1. 你有一个带工具的服务器。
  2. 你的客户也有工具。
  3. 您希望能够同时调用客户端和服务器工具,而不会影响其中任何一个。

在您的服务器上,您可以用实际的工具名称替换反射工具调用,使模型认为它正在调用正确的工具。使用AI-SDK的示例代码:

type ReflectIOShape = {
  id: string;
  name: string;
  input: unknown;
  output: unknown;
};
function convertServerSideToolCallsWithReflection(
  messages: ModelMessage[],
  reflectionToolName: string,
) {
  const toolResultMap = new Map<string, ReflectIOShape>();
  const output = structuredClone(messages);
  for (let i = 0; i < output.length; i++) {
    const message = output[i]!;
    if (message.role === "assistant") {
      if (typeof message.content === "string") continue;
      for (let j = 0; j < message.content.length; j++) {
        const content = message.content[j]!;
        if (content.type === "tool-call") {
          if (content.toolName !== reflectionToolName) continue;
          const payload = content.input as ReflectIOShape;
          toolResultMap.set(payload.id, payload);

          content.toolName = payload.name;
          content.input = payload.input;
        }
        if (content.type === "tool-result") {
          if (content.output.type !== "text") continue;
          if (content.toolName !== reflectionToolName) continue;

          const payload = toolResultMap.get(content.toolCallId);
          if (!payload) continue;

          content.toolName = payload.name;
          content.output = {
            type: "text",
            value: JSON.stringify(payload.output),
          };
        }
      }
    }

    if (message.role === "tool") {
      for (let j = 0; j < message.content.length; j++) {
        const content = message.content[j]!;

        if (content.output.type !== "text") continue;
        if (content.toolName !== reflectionToolName) continue;
        const payload = toolResultMap.get(content.toolCallId);
        if (!payload) continue;
        content.toolName = payload.name;
        content.output = {
          type: "text",
          value: JSON.stringify(payload.output),
        };
      }
    }
  }
  return output;
}