import { getAgentFromSystem } from './chunk-5NBDNR2B.js';
import { listToolsResponseSchema, serializedToolSchema, toolIdPathParams, executeToolResponseSchema, executeToolContextBodySchema, agentToolPathParams, executeToolBodySchema } from './chunk-R3KUPFCO.js';
import { MastraFGAPermissions, validateBody } from './chunk-JBSUT5XF.js';
import { optionalRunIdSchema } from './chunk-2YY3EMMS.js';
import { stringify } from './chunk-QIQWHDPH.js';
import { handleError } from './chunk-7ZWJX3AN.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { standardSchemaToJSONSchema, toStandardSchema5 } from './chunk-YZAQOU2I.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { isVercelTool, isProviderDefinedTool } from '@mastra/core/tools';

// src/server/handlers/tools.ts
var tools_exports = {};
__export(tools_exports, {
  EXECUTE_AGENT_TOOL_ROUTE: () => EXECUTE_AGENT_TOOL_ROUTE,
  EXECUTE_TOOL_ROUTE: () => EXECUTE_TOOL_ROUTE,
  GET_AGENT_TOOL_ROUTE: () => GET_AGENT_TOOL_ROUTE,
  GET_TOOL_BY_ID_ROUTE: () => GET_TOOL_BY_ID_ROUTE,
  LIST_TOOLS_ROUTE: () => LIST_TOOLS_ROUTE
});
function resolveLazySchema(schema) {
  if (typeof schema === "function" && !("~standard" in schema)) {
    return resolveLazySchema(schema());
  }
  return schema;
}
function schemaToJsonSchema(schema) {
  if (!schema) {
    return void 0;
  }
  return standardSchemaToJSONSchema(toStandardSchema5(schema), { target: "draft-2020-12" });
}
function serializeSchema(schema) {
  const jsonSchema = schemaToJsonSchema(resolveLazySchema(schema));
  if (jsonSchema === void 0) return void 0;
  return stringify(jsonSchema);
}
async function findToolInAgents(mastra, toolId, requestContext) {
  const agents = mastra.listAgents() || {};
  for (const agent of Object.values(agents)) {
    try {
      const agentTools = await agent.listTools({ requestContext });
      const found = Object.values(agentTools || {}).find((t) => t.id === toolId);
      if (found) return found;
    } catch (error) {
      mastra.getLogger?.()?.warn?.("Failed to list tools for agent while resolving tool by id", {
        agentId: agent?.id,
        toolId,
        error: error instanceof Error ? error.message : String(error)
      });
    }
  }
  return void 0;
}
function serializeTool(tool) {
  if (isProviderDefinedTool(tool)) {
    const resolvedInput = resolveLazySchema(tool.inputSchema);
    const resolvedOutput = resolveLazySchema(tool.outputSchema);
    return {
      ...tool,
      inputSchema: resolvedInput && typeof resolvedInput === "object" && "jsonSchema" in resolvedInput ? stringify(resolvedInput.jsonSchema) : void 0,
      outputSchema: resolvedOutput && typeof resolvedOutput === "object" && "jsonSchema" in resolvedOutput ? stringify(resolvedOutput.jsonSchema) : void 0
    };
  }
  return {
    ...tool,
    inputSchema: serializeSchema(tool.inputSchema),
    outputSchema: serializeSchema(tool.outputSchema),
    requestContextSchema: serializeSchema(tool.requestContextSchema)
  };
}
var LIST_TOOLS_ROUTE = createRoute({
  method: "GET",
  path: "/tools",
  responseType: "json",
  responseSchema: listToolsResponseSchema,
  summary: "List all tools",
  description: "Returns a list of all available tools in the system",
  tags: ["Tools"],
  requiresAuth: true,
  handler: async ({ mastra, registeredTools, requestContext }) => {
    try {
      const registered = registeredTools && Object.keys(registeredTools).length > 0 ? registeredTools : {};
      const allTools = {};
      const seenToolIds = /* @__PURE__ */ new Map();
      for (const [key, tool] of Object.entries(registered)) {
        const toolId = typeof tool?.id === "string" ? tool.id : void 0;
        if (toolId !== void 0) seenToolIds.set(toolId, key);
        allTools[key] = tool;
      }
      for (const [key, tool] of Object.entries(mastra.listTools() ?? {})) {
        const toolId = typeof tool?.id === "string" ? tool.id : void 0;
        if (toolId !== void 0 && seenToolIds.has(toolId)) continue;
        if (toolId !== void 0) seenToolIds.set(toolId, key);
        allTools[key] = tool;
      }
      const serializedTools = Object.entries(allTools).reduce(
        (acc, [id, _tool]) => {
          acc[id] = serializeTool(_tool);
          return acc;
        },
        {}
      );
      const fgaProvider = mastra.getServer?.()?.fga;
      const user = requestContext?.get("user");
      if (fgaProvider && user) {
        const toolList = Object.entries(serializedTools).map(([id, t]) => ({ id, ...t }));
        const accessible = await fgaProvider.filterAccessible(user, toolList, "tool", MastraFGAPermissions.TOOLS_READ);
        const accessibleSet = new Set(accessible.map((t) => t.id));
        for (const id of Object.keys(serializedTools)) {
          if (!accessibleSet.has(id)) {
            delete serializedTools[id];
          }
        }
      }
      return serializedTools;
    } catch (error) {
      return handleError(error, "Error getting tools");
    }
  }
});
var GET_TOOL_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/tools/:toolId",
  responseType: "json",
  pathParamSchema: toolIdPathParams,
  responseSchema: serializedToolSchema,
  summary: "Get tool by ID",
  description: "Returns details for a specific tool including its schema and configuration",
  tags: ["Tools"],
  requiresAuth: true,
  handler: async ({ mastra, registeredTools, toolId, requestContext }) => {
    try {
      let tool;
      if (registeredTools && Object.keys(registeredTools).length > 0) {
        tool = Object.values(registeredTools).find((t) => t.id === toolId);
      }
      if (!tool) {
        try {
          tool = mastra.getToolById(toolId);
        } catch {
        }
      }
      if (!tool) {
        tool = await findToolInAgents(mastra, toolId, requestContext);
      }
      if (!tool) {
        throw new HTTPException(404, { message: "Tool not found" });
      }
      return serializeTool(tool);
    } catch (error) {
      return handleError(error, "Error getting tool");
    }
  }
});
var EXECUTE_TOOL_ROUTE = createRoute({
  method: "POST",
  path: "/tools/:toolId/execute",
  responseType: "json",
  pathParamSchema: toolIdPathParams,
  queryParamSchema: optionalRunIdSchema,
  bodySchema: executeToolContextBodySchema,
  responseSchema: executeToolResponseSchema,
  summary: "Execute tool",
  description: "Executes a specific tool with the provided input data",
  tags: ["Tools"],
  requiresAuth: true,
  handler: async ({ mastra, runId, toolId, registeredTools, requestContext, ...bodyParams }) => {
    try {
      if (!toolId) {
        throw new HTTPException(400, { message: "Tool ID is required" });
      }
      let tool;
      if (registeredTools && Object.keys(registeredTools).length > 0) {
        tool = Object.values(registeredTools).find((t) => t.id === toolId);
      }
      if (!tool) {
        try {
          tool = mastra.getToolById(toolId);
        } catch {
        }
      }
      if (!tool) {
        tool = await findToolInAgents(mastra, toolId, requestContext);
      }
      if (!tool) {
        throw new HTTPException(404, { message: "Tool not found" });
      }
      if (!tool?.execute) {
        throw new HTTPException(400, { message: "Tool is not executable" });
      }
      const { data } = bodyParams;
      validateBody({ data });
      let result;
      if (isVercelTool(tool)) {
        result = await tool.execute(data);
      } else {
        result = await tool.execute(data, {
          mastra,
          requestContext,
          // TODO: Pass proper tracing context when server API supports tracing
          tracingContext: { currentSpan: void 0 },
          ...runId ? {
            workflow: {
              runId,
              suspend: async () => {
              }
            }
          } : {}
        });
      }
      return result;
    } catch (error) {
      return handleError(error, "Error executing tool");
    }
  }
});
var GET_AGENT_TOOL_ROUTE = createRoute({
  method: "GET",
  path: "/agents/:agentId/tools/:toolId",
  responseType: "json",
  pathParamSchema: agentToolPathParams,
  responseSchema: serializedToolSchema,
  summary: "Get agent tool",
  description: "Returns details for a specific tool assigned to the agent",
  tags: ["Agents", "Tools"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, toolId, requestContext }) => {
    try {
      if (!agentId) {
        throw new HTTPException(400, { message: "Agent ID is required" });
      }
      const agent = await getAgentFromSystem({ mastra, agentId });
      const agentTools = await agent.listTools({ requestContext });
      const tool = Object.values(agentTools || {}).find((tool2) => tool2.id === toolId);
      if (!tool) {
        throw new HTTPException(404, { message: "Tool not found" });
      }
      return serializeTool(tool);
    } catch (error) {
      return handleError(error, "Error getting agent tool");
    }
  }
});
var EXECUTE_AGENT_TOOL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/tools/:toolId/execute",
  responseType: "json",
  pathParamSchema: agentToolPathParams,
  bodySchema: executeToolBodySchema,
  responseSchema: executeToolResponseSchema,
  summary: "Execute agent tool",
  description: "Executes a specific tool assigned to the agent with the provided input data",
  tags: ["Agents", "Tools"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, toolId, data, requestContext }) => {
    try {
      if (!agentId) {
        throw new HTTPException(400, { message: "Agent ID is required" });
      }
      const agent = await getAgentFromSystem({ mastra, agentId });
      const agentTools = await agent.listTools({ requestContext });
      const tool = Object.values(agentTools || {}).find((tool2) => tool2.id === toolId);
      if (!tool) {
        throw new HTTPException(404, { message: "Tool not found" });
      }
      if (!tool?.execute) {
        throw new HTTPException(400, { message: "Tool is not executable" });
      }
      const result = await tool.execute(data, {
        mastra,
        requestContext,
        // TODO: Pass proper tracing context when server API supports tracing
        tracingContext: { currentSpan: void 0 }
      });
      return result;
    } catch (error) {
      return handleError(error, "Error executing agent tool");
    }
  }
});

export { EXECUTE_AGENT_TOOL_ROUTE, EXECUTE_TOOL_ROUTE, GET_AGENT_TOOL_ROUTE, GET_TOOL_BY_ID_ROUTE, LIST_TOOLS_ROUTE, tools_exports };
//# sourceMappingURL=chunk-UZQ2ZJUF.js.map
//# sourceMappingURL=chunk-UZQ2ZJUF.js.map