import {
  _isMcpAvailable,
  _readProjectMcpConfig,
  _mergeMcpServers,
  _loadMcpTools,
  _loadMcpToolsWithStatus
} from "agency-lang/stdlib-lib/mcp.js"

/** @module
  @summary Load MCP tools and report server connection status.
  Read project server settings, merge them with global settings, and load
  tools for use in `llm()`. Calls to loaded tools raise `mcp::call` so handlers
  and policies can approve or reject them.

  ```ts
  import { readProjectMcpConfig, loadMcpToolsWithStatus } from "std::mcp"

  const servers = readProjectMcpConfig(".")
  const loaded = loadMcpToolsWithStatus(servers)
  printJSON(loaded.status)
  ```
*/

/** Loaded tools and each server's "connected" or "unavailable" status. */
export type McpLoadResult = {
  tools: any[];
  status: Record<string, string>
}

// The effect an MCP tool call raises before its JSON-RPC fires. Raised from TS
// (lib/stdlib/mcpGate.ts) via agency.interrupt with this exact name; declared
// here so handlers can match the effect and inspect its server, tool, and args.
@always(server, tool)
effect mcp::call {
  server: string,
  tool: string,
  args: Record<string, any>
}

export def isMcpAvailable(): boolean {
  """True when the @agency-lang/mcp package is installed and reachable."""
  return _isMcpAvailable()
}

@capabilities(fileRead)
export def readProjectMcpConfig(dir: string): Record<string, any> {
  """Read the mcpServers block from the project agency.json under `dir`."""
  return _readProjectMcpConfig(dir)
}

export def mergeMcpServers(global: Record<string, any>, project: Record<string, any>): Record<string, any> {
  """Merge global and project mcpServers configs (project wins on collision)."""
  return _mergeMcpServers(global, project)
}

@capabilities(fileRead, fileWrite, network, subprocess)
export def loadMcpTools(merged: Record<string, any>, onOAuthRequired?): any[] {
  """Load gated MCP tools for every server in `merged`. Returns [] when the
  package is absent, incompatible, or no servers are configured."""
  return _loadMcpTools(merged, onOAuthRequired)
}

@capabilities(fileRead, fileWrite, network, subprocess)
export def loadMcpToolsWithStatus(merged: Record<string, any>, onOAuthRequired?): McpLoadResult {
  """
  Load MCP tools and report which servers connected.

  @param merged - Server configurations, such as the output of mergeMcpServers.
  """
  return _loadMcpToolsWithStatus(merged, onOAuthRequired)
}
