import {
  MCP_RESOURCES,
  MCP_TOOLS,
  callMcpTool,
  readMcpResource
} from "./chunk-PKCYTOHW.js";
import "./chunk-CBLBQP27.js";

// ../../hosts/host-mcp/src/http.ts
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";

// ../../hosts/host-mcp/src/server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
  CallToolRequestSchema,
  ListResourcesRequestSchema,
  ListToolsRequestSchema,
  ReadResourceRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
var BEARER_PREFIX = /^Bearer\s+/i;
function bearerFrom(headers) {
  if (headers === void 0) return void 0;
  const raw = headers["authorization"] ?? headers["Authorization"];
  const value = Array.isArray(raw) ? raw[0] : raw;
  if (value === void 0) return void 0;
  const match = BEARER_PREFIX.exec(value);
  return match ? value.slice(match[0].length).trim() : void 0;
}
function createMcpServer(deps, identity) {
  const server = new Server(
    { name: identity?.name ?? "nanoesis", version: identity?.version ?? "0.0.0" },
    { capabilities: { tools: {}, resources: {} } }
  );
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [...MCP_TOOLS] }));
  server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
    const args = req.params.arguments ?? {};
    const token = bearerFrom(extra.requestInfo?.headers);
    const result = await callMcpTool(
      deps,
      req.params.name,
      args,
      token !== void 0 ? { token } : {}
    );
    return { content: [{ type: "text", text: result.text }], isError: result.isError };
  });
  server.setRequestHandler(ListResourcesRequestSchema, async () => ({
    resources: [...MCP_RESOURCES]
  }));
  server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
    const { uri } = req.params;
    const resource = readMcpResource(uri);
    if (resource === void 0) throw new Error(`Unknown resource: ${uri}`);
    return { contents: [{ uri, mimeType: resource.mimeType, text: resource.text }] };
  });
  return server;
}

// ../../hosts/host-mcp/src/http.ts
var DEFAULT_VERSION = true ? "0.1.15" : "0.0.0-workspace";
async function handleMcpRequest(deps, request, opts) {
  const server = createMcpServer(deps, {
    name: opts?.name ?? "nanoesis",
    version: opts?.version ?? DEFAULT_VERSION
  });
  const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
  await server.connect(transport);
  try {
    return await transport.handleRequest(request);
  } finally {
    await transport.close();
    await server.close();
  }
}
export {
  handleMcpRequest
};
