import { getAgentFromSystem } from './chunk-LP3TMC5I.js';
import { listToolsResponseSchema, serializedToolSchema, toolIdPathParams, executeToolResponseSchema, executeToolContextBodySchema, agentToolPathParams, executeToolBodySchema } from './chunk-HXRJMA6T.js';
import { validateBody } from './chunk-USR6JK77.js';
import { stringify } from './chunk-LII44FTI.js';
import { optionalRunIdSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { isVercelTool } from '@mastra/core/tools';
import { zodToJsonSchema } from '@mastra/core/utils/zod-to-json';

// 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
});
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 }) => {
    try {
      const allTools = registeredTools || mastra.listTools() || {};
      const serializedTools = Object.entries(allTools).reduce(
        (acc, [id, _tool]) => {
          const tool = _tool;
          acc[id] = {
            ...tool,
            inputSchema: tool.inputSchema ? stringify(zodToJsonSchema(tool.inputSchema)) : void 0,
            outputSchema: tool.outputSchema ? stringify(zodToJsonSchema(tool.outputSchema)) : void 0,
            requestContextSchema: tool.requestContextSchema ? stringify(zodToJsonSchema(tool.requestContextSchema)) : void 0
          };
          return acc;
        },
        {}
      );
      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 }) => {
    try {
      let tool;
      if (registeredTools && Object.keys(registeredTools).length > 0) {
        tool = Object.values(registeredTools).find((t) => t.id === toolId);
      } else {
        tool = mastra.getToolById(toolId);
      }
      if (!tool) {
        throw new HTTPException(404, { message: "Tool not found" });
      }
      const serializedTool = {
        ...tool,
        inputSchema: tool.inputSchema ? stringify(zodToJsonSchema(tool.inputSchema)) : void 0,
        outputSchema: tool.outputSchema ? stringify(zodToJsonSchema(tool.outputSchema)) : void 0,
        requestContextSchema: tool.requestContextSchema ? stringify(zodToJsonSchema(tool.requestContextSchema)) : void 0
      };
      return serializedTool;
    } 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);
      } else {
        tool = mastra.getToolById(toolId);
      }
      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 });
      if (isVercelTool(tool)) {
        const result2 = await tool.execute(data);
        return result2;
      }
      const 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" });
      }
      const serializedTool = {
        ...tool,
        inputSchema: tool.inputSchema ? stringify(zodToJsonSchema(tool.inputSchema)) : void 0,
        outputSchema: tool.outputSchema ? stringify(zodToJsonSchema(tool.outputSchema)) : void 0,
        requestContextSchema: tool.requestContextSchema ? stringify(zodToJsonSchema(tool.requestContextSchema)) : void 0
      };
      return serializedTool;
    } 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-AR4SLO57.js.map
//# sourceMappingURL=chunk-AR4SLO57.js.map