|
| 1 | +defmodule Core.MCP.Server do |
| 2 | + use MCPServer |
| 3 | + alias Core.MCP.Tools.{ |
| 4 | + Account, |
| 5 | + Enterprise, |
| 6 | + CloudConsole, |
| 7 | + RemoveEnterprise |
| 8 | + } |
| 9 | + |
| 10 | + @tools [Account, Enterprise, CloudConsole, RemoveEnterprise] |
| 11 | + @by_name Map.new(@tools, & {&1.name(), &1}) |
| 12 | + |
| 13 | + @protocol_version "2024-11-05" |
| 14 | + |
| 15 | + @impl true |
| 16 | + def handle_ping(request_id) do |
| 17 | + {:ok, %{jsonrpc: "2.0", id: request_id, result: %{}}} |
| 18 | + end |
| 19 | + |
| 20 | + @impl true |
| 21 | + def handle_initialize(request_id, params) do |
| 22 | + case validate_protocol_version(params["protocolVersion"]) do |
| 23 | + :ok -> |
| 24 | + {:ok, |
| 25 | + %{ |
| 26 | + jsonrpc: "2.0", |
| 27 | + id: request_id, |
| 28 | + result: %{ |
| 29 | + protocolVersion: @protocol_version, |
| 30 | + capabilities: %{ |
| 31 | + tools: %{ |
| 32 | + listChanged: true |
| 33 | + } |
| 34 | + }, |
| 35 | + serverInfo: %{ |
| 36 | + name: "Plural MCP Server", |
| 37 | + version: "0.1.0" |
| 38 | + } |
| 39 | + } |
| 40 | + }} |
| 41 | + |
| 42 | + {:error, reason} -> |
| 43 | + {:error, reason} |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + @impl true |
| 48 | + def handle_list_tools(request_id, _params) do |
| 49 | + tools = Enum.map(@tools, & %{ |
| 50 | + name: &1.name(), |
| 51 | + description: &1.description(), |
| 52 | + inputSchema: &1.schema() |
| 53 | + }) |
| 54 | + {:ok, %{jsonrpc: "2.0", id: request_id, result: %{tools: tools}}} |
| 55 | + end |
| 56 | + |
| 57 | + @impl true |
| 58 | + def handle_call_tool(request_id, %{"name" => name} = params) do |
| 59 | + with {:tool, t} when not is_nil(t) <- {:tool, @by_name[name]}, |
| 60 | + {:ok, result} <- t.invoke(params["arguments"]) do |
| 61 | + {:ok, %{jsonrpc: "2.0", id: request_id, result: %{content: [%{type: "text", text: result}]}}} |
| 62 | + else |
| 63 | + {:tool, _} -> |
| 64 | + {:error, %{ |
| 65 | + jsonrpc: "2.0", |
| 66 | + id: request_id, |
| 67 | + error: %{ |
| 68 | + code: -32601, |
| 69 | + message: "Method not found", |
| 70 | + data: %{ |
| 71 | + name: "no tool with name #{name}" |
| 72 | + } |
| 73 | + } |
| 74 | + }} |
| 75 | + {:error, err} -> |
| 76 | + {:ok, %{jsonrpc: "2.0", id: request_id, result: %{isError: true, content: [%{type: "text", text: err}]}}} |
| 77 | + end |
| 78 | + end |
| 79 | +end |
0 commit comments