'use strict';

var chunkEFJCOPJ3_cjs = require('./chunk-EFJCOPJ3.cjs');
var chunkZQ4GVMYG_cjs = require('./chunk-ZQ4GVMYG.cjs');
var chunk42M6Y2OD_cjs = require('./chunk-42M6Y2OD.cjs');
var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs');
var chunkDRDVJ35H_cjs = require('./chunk-DRDVJ35H.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk22EM2GBH_cjs = require('./chunk-22EM2GBH.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var tools = require('@mastra/core/tools');

// src/server/handlers/tools.ts
var tools_exports = {};
chunkO7I5CWRX_cjs.__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 chunk22EM2GBH_cjs.standardSchemaToJSONSchema(chunk22EM2GBH_cjs.toStandardSchema5(schema), { target: "draft-2020-12" });
}
function serializeSchema(schema) {
  const jsonSchema = schemaToJsonSchema(resolveLazySchema(schema));
  if (jsonSchema === void 0) return void 0;
  return chunkDRDVJ35H_cjs.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 (tools.isProviderDefinedTool(tool)) {
    const resolvedInput = resolveLazySchema(tool.inputSchema);
    const resolvedOutput = resolveLazySchema(tool.outputSchema);
    return {
      ...tool,
      inputSchema: resolvedInput && typeof resolvedInput === "object" && "jsonSchema" in resolvedInput ? chunkDRDVJ35H_cjs.stringify(resolvedInput.jsonSchema) : void 0,
      outputSchema: resolvedOutput && typeof resolvedOutput === "object" && "jsonSchema" in resolvedOutput ? chunkDRDVJ35H_cjs.stringify(resolvedOutput.jsonSchema) : void 0
    };
  }
  return {
    ...tool,
    inputSchema: serializeSchema(tool.inputSchema),
    outputSchema: serializeSchema(tool.outputSchema),
    requestContextSchema: serializeSchema(tool.requestContextSchema)
  };
}
var LIST_TOOLS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/tools",
  responseType: "json",
  responseSchema: chunkZQ4GVMYG_cjs.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", chunk42M6Y2OD_cjs.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 chunkZ7LCIYK7_cjs.handleError(error, "Error getting tools");
    }
  }
});
var GET_TOOL_BY_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/tools/:toolId",
  responseType: "json",
  pathParamSchema: chunkZQ4GVMYG_cjs.toolIdPathParams,
  responseSchema: chunkZQ4GVMYG_cjs.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 chunk64ITUOXI_cjs.HTTPException(404, { message: "Tool not found" });
      }
      return serializeTool(tool);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting tool");
    }
  }
});
var EXECUTE_TOOL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/tools/:toolId/execute",
  responseType: "json",
  pathParamSchema: chunkZQ4GVMYG_cjs.toolIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.optionalRunIdSchema,
  bodySchema: chunkZQ4GVMYG_cjs.executeToolContextBodySchema,
  responseSchema: chunkZQ4GVMYG_cjs.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 chunk64ITUOXI_cjs.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 chunk64ITUOXI_cjs.HTTPException(404, { message: "Tool not found" });
      }
      if (!tool?.execute) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool is not executable" });
      }
      const { data } = bodyParams;
      chunk42M6Y2OD_cjs.validateBody({ data });
      let result;
      if (tools.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 chunkZ7LCIYK7_cjs.handleError(error, "Error executing tool");
    }
  }
});
var GET_AGENT_TOOL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/agents/:agentId/tools/:toolId",
  responseType: "json",
  pathParamSchema: chunkZQ4GVMYG_cjs.agentToolPathParams,
  responseSchema: chunkZQ4GVMYG_cjs.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 chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent ID is required" });
      }
      const agent = await chunkEFJCOPJ3_cjs.getAgentFromSystem({ mastra, agentId });
      const agentTools = await agent.listTools({ requestContext });
      const tool = Object.values(agentTools || {}).find((tool2) => tool2.id === toolId);
      if (!tool) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Tool not found" });
      }
      return serializeTool(tool);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting agent tool");
    }
  }
});
var EXECUTE_AGENT_TOOL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/tools/:toolId/execute",
  responseType: "json",
  pathParamSchema: chunkZQ4GVMYG_cjs.agentToolPathParams,
  bodySchema: chunkZQ4GVMYG_cjs.executeToolBodySchema,
  responseSchema: chunkZQ4GVMYG_cjs.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 chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent ID is required" });
      }
      const agent = await chunkEFJCOPJ3_cjs.getAgentFromSystem({ mastra, agentId });
      const agentTools = await agent.listTools({ requestContext });
      const tool = Object.values(agentTools || {}).find((tool2) => tool2.id === toolId);
      if (!tool) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Tool not found" });
      }
      if (!tool?.execute) {
        throw new chunk64ITUOXI_cjs.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 chunkZ7LCIYK7_cjs.handleError(error, "Error executing agent tool");
    }
  }
});

exports.EXECUTE_AGENT_TOOL_ROUTE = EXECUTE_AGENT_TOOL_ROUTE;
exports.EXECUTE_TOOL_ROUTE = EXECUTE_TOOL_ROUTE;
exports.GET_AGENT_TOOL_ROUTE = GET_AGENT_TOOL_ROUTE;
exports.GET_TOOL_BY_ID_ROUTE = GET_TOOL_BY_ID_ROUTE;
exports.LIST_TOOLS_ROUTE = LIST_TOOLS_ROUTE;
exports.tools_exports = tools_exports;
//# sourceMappingURL=chunk-MJS4T74S.cjs.map
//# sourceMappingURL=chunk-MJS4T74S.cjs.map