├── .formatter.exs ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── config └── config.exs ├── lib ├── mcp_proxy.ex └── mcp_proxy │ └── sse.ex ├── mix.exs ├── mix.lock └── test ├── mcp_proxy_test.exs ├── support └── sse_server.ex └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Elixir CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | name: Build and test 16 | runs-on: ubuntu-latest 17 | 18 | strategy: 19 | matrix: 20 | include: 21 | - elixir: 1.15.8 22 | otp: 26.2 23 | 24 | - elixir: 1.18.2 25 | otp: 27.2 26 | lint: lint 27 | 28 | env: 29 | MIX_ENV: test 30 | 31 | steps: 32 | - uses: actions/checkout@v4 33 | - name: Set up Elixir 34 | uses: erlef/setup-beam@v1 35 | with: 36 | elixir-version: ${{ matrix.elixir }} 37 | otp-version: ${{ matrix.otp }} 38 | 39 | - name: Restore deps and _build cache 40 | uses: actions/cache@v4 41 | with: 42 | path: | 43 | deps 44 | _build 45 | key: deps-${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('**/mix.lock') }} 46 | restore-keys: | 47 | deps-${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }} 48 | 49 | - name: Install dependencies 50 | run: mix deps.get 51 | 52 | - name: Remove compiled application files 53 | run: mix clean 54 | 55 | - name: Compile 56 | run: mix compile 57 | if: ${{ !matrix.lint }} 58 | 59 | - name: Compile & lint 60 | run: mix compile --warnings-as-errors 61 | if: ${{ matrix.lint }} 62 | 63 | - name: Check if formatted 64 | run: mix format --check-formatted 65 | if: ${{ matrix.lint }} 66 | 67 | - name: Check for unused deps 68 | run: mix deps.unlock --check-unused 69 | 70 | - name: Run tests 71 | run: mix test --warnings-as-errors 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # If the VM crashes, it generates a dump, let's ignore it too. 14 | erl_crash.dump 15 | 16 | # Also ignore archive artifacts (built via "mix archive.build"). 17 | *.ez 18 | 19 | # Ignore package tarball (built via "mix hex.build"). 20 | mcp_proxy-*.tar 21 | 22 | # Temporary files, for example, from tests. 23 | /tmp/ 24 | 25 | # Escript 26 | /mcp-proxy -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.3.3 (2025-05-02) 4 | 5 | * Bug fixes 6 | * Ignore SSE comment lines 7 | * Handle notifications while the server is disconnected 8 | 9 | ## 0.3.2 (2025-04-29) 10 | 11 | * Bug fixes 12 | * Allow relative URLs in MCP endpoint event 13 | * Try to parse any event type, not only `message` 14 | 15 | ## 0.3.1 (2025-04-26) 16 | 17 | * Enhancements 18 | * add configurable `--receive-timeout` for POST requests (defaults to 60 seconds). 19 | Note: the proxy will reply to the MCP request with an error response and discard 20 | the real response if it arrives after the timeout. Previously, POST requests timed 21 | out after 15 seconds. 22 | 23 | ## 0.3.0 (2025-04-23) 24 | 25 | * Enhancements 26 | * Automatically try to reconnect when the SSE connection closes. 27 | This can be adjusted by setting the `--max-disconnected-time` parameter, 28 | which defines the number of seconds the proxy tries to reconnect. By default, it retries 29 | indefinitely. To close the proxy on disconnect, this value can be set to `0`. 30 | * Notice: in order to support reconnects, the proxy transparently rewrites the IDs of 31 | received and sent JSON ID messages. 32 | 33 | ## 0.2.0 (2025-04-22) 34 | 35 | * API adjustments 36 | * the escript is called `mcp-proxy` instead of `mcp_proxy` now 37 | * remove `--url` flag and use first argument instead: `mcp-proxy http://localhost:4000/tidewave/mcp` 38 | * Bug fixes: 39 | * ensure script terminates early when SSE connection closes 40 | 41 | ## 0.1.0 (2025-04-14) 42 | 43 | Initial release. 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > [!WARNING] 2 | > This project is deprecated. Use [the Rust MCP Proxy](https://github.com/tidewave-ai/mcp_proxy_rust) instead, which is easier to install if you don't already have Elixir. 3 | 4 | # mcp-proxy 5 | 6 | An Elixir escript for connecting STDIO based MCP clients to HTTP (SSE) based MCP servers. 7 | 8 | Note: At the moment this only works with MCP servers that use the `2024-11-05` specification. 9 | 10 | ## Installation 11 | 12 | ```bash 13 | $ mix escript.install hex mcp_proxy 14 | ``` 15 | 16 | The escript is installed into your HOME's `.mix` directory: `/path/to/home/.mix/escripts/mcp-proxy`. 17 | 18 | ## Usage 19 | 20 | If you have an SSE MCP server available at `http://localhost:4000/tidewave/mcp`, a client like Claude Desktop would then be configured as follows. 21 | 22 | ### On macos/Linux 23 | 24 | You will also need to know the location of the `escript` executable, so run `which escript` before to get the value of "path/to/escript": 25 | 26 | ```json 27 | { 28 | "mcpServers": { 29 | "my-server": { 30 | "command": "/path/to/escript", 31 | "args": ["/$HOME/.mix/escripts/mcp-proxy", "http://localhost:4000/tidewave/mcp"] 32 | } 33 | } 34 | } 35 | ``` 36 | 37 | Remember to replace `$HOME` by your home directory, such as "/Users/johndoe". 38 | 39 | ### On Windows 40 | 41 | ```json 42 | { 43 | "mcpServers": { 44 | "my-server": { 45 | "command": "escript.exe", 46 | "args": ["c:\$HOME\.mix\escripts\mcp-proxy", "http://localhost:4000/tidewave/mcp"] 47 | } 48 | } 49 | } 50 | ``` 51 | 52 | Remember to replace `$HOME` by your home directory, such as "c:\Users\johndoe". 53 | 54 | ## Configuration 55 | 56 | `mcp-proxy` either accepts the SSE URL as argument or using the environment variable `SSE_URL`. For debugging purposes, you can also pass `--debug`, which will log debug messages on stderr. 57 | 58 | Other supported flags: 59 | 60 | * `--max-disconnected-time` the maximum amount of time for trying to reconnect while disconnected. When not set, defaults to infinity. 61 | * `--receive-timeout` the maximum amount of time to wait for an individual reply from the MCP server in milliseconds. Defaults to 60000 (60 seconds). 62 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | config :logger, :default_handler, 4 | config: [ 5 | type: :standard_error 6 | ] 7 | -------------------------------------------------------------------------------- /lib/mcp_proxy.ex: -------------------------------------------------------------------------------- 1 | defmodule McpProxy do 2 | @moduledoc false 3 | require Logger 4 | 5 | alias McpProxy.SSE 6 | 7 | @doc false 8 | def main(args) do 9 | {opts, args} = 10 | OptionParser.parse!(args, 11 | strict: [ 12 | debug: :boolean, 13 | max_disconnected_time: :integer, 14 | receive_timeout: :integer 15 | ] 16 | ) 17 | 18 | base_url = 19 | case args do 20 | [arg_url] -> 21 | arg_url 22 | 23 | [] -> 24 | System.get_env("SSE_URL") || 25 | raise "either the URL is passed as first argument or the SSE_URL environment variable must be set" 26 | 27 | many -> 28 | raise "expected one or zero arguments, got: #{inspect(many)}" 29 | end 30 | 31 | Application.ensure_all_started(:req) 32 | Application.put_all_env(mcp_proxy: opts) 33 | 34 | {:ok, handler} = SSE.start_link(base_url) 35 | ref = Process.monitor(handler) 36 | 37 | receive do 38 | {:DOWN, ^ref, _, _, reason} -> 39 | System.stop((reason == :normal && 0) || 1) 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /lib/mcp_proxy/sse.ex: -------------------------------------------------------------------------------- 1 | defmodule McpProxy.SSE do 2 | @moduledoc false 3 | 4 | use GenServer 5 | 6 | require Logger 7 | 8 | # unused, just for documentation purposes 9 | @type state :: %{ 10 | url: binary(), 11 | endpoint: binary() | nil, 12 | debug: boolean(), 13 | max_disconnected_time: integer() | nil, 14 | disconnected_since: DateTime.t() | nil, 15 | state: 16 | :connecting 17 | | :connected 18 | | :waiting_for_endpoint 19 | | :waiting_for_client_init 20 | | {:waiting_for_server_init, binary() | integer()} 21 | | {:waiting_for_server_init_hidden, binary() | integer()} 22 | | :waiting_for_client_initialized, 23 | connect_tries: non_neg_integer(), 24 | init_message: nil | map(), 25 | id_map: map(), 26 | io_pid: pid() | nil, 27 | http_pid: pid() | nil, 28 | in_buf: list(), 29 | buf_mode: :store | :fail 30 | } 31 | 32 | def start_link(arg) do 33 | GenServer.start_link(__MODULE__, arg) 34 | end 35 | 36 | @impl true 37 | def init(sse_url) do 38 | {:ok, 39 | %{ 40 | url: sse_url, 41 | endpoint: nil, 42 | debug: Application.get_env(:mcp_proxy, :debug, false), 43 | max_disconnected_time: Application.get_env(:mcp_proxy, :max_disconnected_time), 44 | disconnected_since: nil, 45 | state: :connecting, 46 | connect_tries: 0, 47 | # the init message is replayed when reconnecting 48 | init_message: nil, 49 | id_map: %{}, 50 | io_pid: nil, 51 | http_pid: nil, 52 | in_buf: [], 53 | buf_mode: :store 54 | }, {:continue, :connect_to_sse}} 55 | end 56 | 57 | defguardp is_request(map) when is_map_key(map, "id") and is_map_key(map, "method") 58 | 59 | defguardp is_response(map) 60 | when is_map_key(map, "id") and (is_map_key(map, "result") or is_map_key(map, "error")) 61 | 62 | @impl true 63 | def handle_continue(:connect_to_sse, %{http_pid: nil} = state) do 64 | if state.debug, do: Logger.debug("Connecting to SSE: #{state.url}") 65 | 66 | {:noreply, spawn_http_process(state)} 67 | end 68 | 69 | def handle_continue(:flush_in_buf, %{in_buf: in_buf} = state) do 70 | if state.debug, do: Logger.debug("Flushing buffer: #{length(in_buf)} messages") 71 | 72 | for event <- Enum.reverse(in_buf) do 73 | send(self(), {:io_event, event}) 74 | end 75 | 76 | {:noreply, %{state | in_buf: []}} 77 | end 78 | 79 | defp spawn_http_process(state) do 80 | if state.debug, do: Logger.debug("Starting HTTP process") 81 | 82 | parent = self() 83 | 84 | pid = 85 | spawn(fn -> 86 | Req.new() 87 | |> Req.get!( 88 | url: state.url, 89 | headers: [{"accept", "text/event-stream"}], 90 | into: fn {:data, chunk}, {req, resp} -> 91 | process_sse_chunk(chunk, parent, state.debug) 92 | # Return {:cont, {req, resp}} to continue streaming 93 | {:cont, {req, resp}} 94 | end, 95 | receive_timeout: :infinity, 96 | retry: false 97 | ) 98 | end) 99 | 100 | Process.monitor(pid) 101 | 102 | %{state | http_pid: pid, state: :waiting_for_endpoint} 103 | end 104 | 105 | defp process_sse_chunk(chunk, parent, debug) do 106 | if debug, do: Logger.debug("Received SSE chunk: #{inspect(chunk)}") 107 | 108 | # Split the chunk into lines and process each event 109 | chunk 110 | |> String.split("\n\n", trim: true) 111 | |> Enum.each(fn event_data -> 112 | case parse_sse_event(event_data) do 113 | {:ok, "endpoint", endpoint} -> 114 | if debug, do: Logger.debug("Found endpoint: #{endpoint}") 115 | send(parent, {:sse_event, {:endpoint, endpoint}}) 116 | 117 | {:ok, "message", data} -> 118 | decoded = Jason.decode!(data) 119 | send(parent, {:sse_event, {:message, decoded}}) 120 | 121 | {:ok, event_type, data} -> 122 | if debug, 123 | do: Logger.debug("Received unexpected SSE event: #{event_type}, data: #{data};") 124 | 125 | case Jason.decode(data) do 126 | {:ok, decoded} -> 127 | # assuming it is a regular message 128 | send(parent, {:sse_event, {:message, decoded}}) 129 | 130 | _ -> 131 | Logger.error("Failed to parse SSE event!") 132 | end 133 | 134 | :ignore -> 135 | Logger.debug("Ignoring SSE line: #{inspect(event_data)}") 136 | :ok 137 | 138 | {:error, error} -> 139 | if debug, do: Logger.debug("Error parsing SSE event: #{inspect(error)}") 140 | end 141 | end) 142 | end 143 | 144 | # messages starting with : are considered to be comments 145 | # https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format 146 | defp parse_sse_event(":" <> _), do: :ignore 147 | 148 | defp parse_sse_event(data) do 149 | lines = String.split(data, "\n", trim: true) 150 | 151 | event_type = 152 | lines 153 | |> Enum.find(fn line -> String.starts_with?(line, "event:") end) 154 | |> case do 155 | nil -> "message" 156 | line -> String.trim(String.replace_prefix(line, "event:", "")) 157 | end 158 | 159 | data_line = 160 | lines 161 | |> Enum.find(fn line -> String.starts_with?(line, "data:") end) 162 | |> case do 163 | nil -> nil 164 | line -> String.trim(String.replace_prefix(line, "data:", "")) 165 | end 166 | 167 | case data_line do 168 | nil -> {:error, "No data found in SSE event"} 169 | data -> {:ok, event_type, data} 170 | end 171 | end 172 | 173 | defp spawn_io_process(state) do 174 | if state.debug, do: Logger.debug("Starting IO process") 175 | 176 | parent = self() 177 | pid = spawn_link(fn -> io_loop(parent) end) 178 | 179 | %{state | io_pid: pid} 180 | end 181 | 182 | defp io_loop(parent) do 183 | case IO.read(:stdio, :line) do 184 | :eof -> 185 | :eof 186 | 187 | {:error, reason} -> 188 | send(parent, {:io_error, reason}) 189 | 190 | line -> 191 | send(parent, {:io_event, Jason.decode!(line)}) 192 | io_loop(parent) 193 | end 194 | end 195 | 196 | @impl true 197 | def handle_info( 198 | {:sse_event, {:endpoint, endpoint}}, 199 | %{state: :waiting_for_endpoint} = state 200 | ) do 201 | endpoint = 202 | state.url 203 | |> URI.new!() 204 | |> URI.merge(endpoint) 205 | |> URI.to_string() 206 | 207 | if init_message = state.init_message do 208 | # this is a reconnect, as we already have an init message stored 209 | # therefore we forward the existing message to the server and wait in 210 | # the special :waiting_for_server_init_hidden state, that discards the response 211 | forward_message(init_message, endpoint, state.debug) 212 | 213 | {:noreply, 214 | %{state | state: {:waiting_for_server_init_hidden, init_message["id"]}, endpoint: endpoint}} 215 | else 216 | if state.debug, do: Logger.debug("waiting for client init") 217 | {:noreply, %{spawn_io_process(state) | endpoint: endpoint, state: :waiting_for_client_init}} 218 | end 219 | end 220 | 221 | def handle_info( 222 | {:io_event, %{"method" => "initialize", "id" => client_id} = init_message}, 223 | %{state: :waiting_for_client_init} = state 224 | ) do 225 | if state.debug, 226 | do: Logger.debug("Got client init: #{inspect(init_message)}") 227 | 228 | forward_message(init_message, state.endpoint, state.debug) 229 | 230 | {:noreply, 231 | %{state | state: {:waiting_for_server_init, client_id}, init_message: init_message}} 232 | end 233 | 234 | # initialization reply 235 | def handle_info( 236 | {:sse_event, {:message, %{"id" => init_id} = message}}, 237 | %{state: {:waiting_for_server_init, init_id}} = state 238 | ) do 239 | IO.puts(Jason.encode!(message)) 240 | 241 | {:noreply, %{state | state: :waiting_for_client_initialized}} 242 | end 243 | 244 | # this is the init reply, but we are reconnecting (waiting_for_server_init_hidden), 245 | # so we don't actually forward it to the client 246 | def handle_info( 247 | {:sse_event, {:message, %{"id" => init_id}}}, 248 | %{state: {:waiting_for_server_init_hidden, init_id}} = state 249 | ) do 250 | # for protocol compliance, we need to also send the initialized notification 251 | forward_message( 252 | %{"method" => "notifications/initialized", "jsonrpc" => "2.0"}, 253 | state.endpoint, 254 | state.debug 255 | ) 256 | 257 | {:noreply, connected_state(state), {:continue, :flush_in_buf}} 258 | end 259 | 260 | def handle_info({:io_event, %{"method" => "notifications/initialized"} = event}, state) do 261 | forward_message(event, state.endpoint, state.debug) 262 | 263 | {:noreply, connected_state(state), {:continue, :flush_in_buf}} 264 | end 265 | 266 | # store or reply with an error for events coming from the client 267 | # while we are not connected 268 | def handle_info({:io_event, event}, state) 269 | when state.state not in [:connected, :waiting_for_client_init] do 270 | case event do 271 | %{"method" => "ping", "id" => request_id} -> 272 | # we directly answer ping requests 273 | IO.puts(Jason.encode!(%{jsonrpc: "2.0", id: request_id, result: %{}})) 274 | {:noreply, state} 275 | 276 | %{"method" => "tools/call"} when state.buf_mode == :store -> 277 | # we store tool calls for later 278 | {:noreply, %{state | in_buf: [event | state.in_buf]}} 279 | 280 | %{"method" => _other, "id" => request_id} -> 281 | # we answer with an error 282 | reply_disconnected(request_id) 283 | 284 | {:noreply, state} 285 | 286 | %{"method" => _other} -> 287 | Logger.debug("Ignoring notification while disconnected: #{inspect(event)}") 288 | # ignore notifications 289 | {:noreply, state} 290 | end 291 | end 292 | 293 | # regular events 294 | def handle_info({:sse_event, {:message, event}}, state) do 295 | handle_event(event, state, {&IO.puts(Jason.encode!(&1)), fn _ -> :ok end}) 296 | end 297 | 298 | def handle_info({:io_event, event}, state) do 299 | handle_event( 300 | event, 301 | state, 302 | {&forward_message(&1, state.endpoint, state.debug), &IO.puts(Jason.encode!(&1))} 303 | ) 304 | end 305 | 306 | # whenever the HTTP process dies, we try to reconnect 307 | def handle_info({:DOWN, _ref, :process, http_pid, _reason}, %{http_pid: http_pid} = state) do 308 | backoff = min(2 ** state.connect_tries, 8) 309 | 310 | Logger.info("SSE connection closed. Trying to reconnect in #{backoff}s.") 311 | Process.send_after(self(), :reconnect, backoff * 1000) 312 | 313 | if state.connect_tries == 0 do 314 | # we give the server 20 seconds to reconnect and store incoming 315 | # tool calls, but after that we reply with an error 316 | Process.send_after(self(), :fail_flush, 20_000) 317 | end 318 | 319 | if disconnected_too_long?(state) do 320 | {:stop, {:shutdown, :reconnect_timeout}, state} 321 | else 322 | {:noreply, 323 | %{ 324 | state 325 | | state: :disconnected, 326 | endpoint: nil, 327 | http_pid: nil, 328 | disconnected_since: state.disconnected_since || DateTime.utc_now(), 329 | connect_tries: state.connect_tries + 1 330 | }} 331 | end 332 | end 333 | 334 | # whenever the IO process dies, we can stop, as this means that 335 | # the client itself disconnected 336 | def handle_info({:DOWN, _ref, :process, io_pid, _reason}, %{io_pid: io_pid} = state) do 337 | {:stop, :normal, state} 338 | end 339 | 340 | def handle_info(:reconnect, state) do 341 | {:noreply, state, {:continue, :connect_to_sse}} 342 | end 343 | 344 | def handle_info({:io_error, error}, state) do 345 | Logger.error("Error reading from stdin: #{inspect(error)}") 346 | {:stop, {:shutdown, :io_error}, state} 347 | end 348 | 349 | def handle_info(:fail_flush, state) do 350 | Logger.info("Did not reconnect in time. Flushing buffer, replying with errors!") 351 | 352 | for message <- state.in_buf do 353 | reply_disconnected(message["id"]) 354 | end 355 | 356 | {:noreply, %{state | in_buf: [], buf_mode: :fail}} 357 | end 358 | 359 | # json rpc batch (we don't necessarily need to handle this, as we only expect the 2024-11-05 protocol for now) 360 | defp handle_event(messages, state, handler) when is_list(messages) do 361 | Enum.reduce(messages, state, fn message, state -> handle_event(message, state, handler) end) 362 | end 363 | 364 | defp handle_event(%{"jsonrpc" => "2.0", "id" => request_id} = event, state, {req, resp}) 365 | when is_request(event) do 366 | # whenever we get a request from the client (OR the server!) 367 | # we generate a random ID to prevent duplicate IDs, for example when 368 | # a reconnected server decides to send a ping and always starts with ID 0 369 | new_id = random_id!() 370 | event = Map.put(event, "id", new_id) 371 | 372 | state = 373 | case req.(event) do 374 | :ok -> 375 | %{state | id_map: Map.put(state.id_map, new_id, request_id)} 376 | 377 | {:reply_error, reply} -> 378 | resp.(Map.put(reply, "id", request_id)) 379 | # we don't store the new_id when we already replied to prevent duplicates; 380 | # instead, we'll log an error if a server reply is received later and we already 381 | # replied 382 | state 383 | end 384 | 385 | {:noreply, state} 386 | end 387 | 388 | defp handle_event(%{"jsonrpc" => "2.0", "id" => response_id} = event, state, {handler, _}) 389 | when is_response(event) do 390 | # whenever we receive a response (from the client or server) 391 | # we fetch the original ID from the id map to present the expected 392 | # ID in the reply 393 | case state.id_map do 394 | %{^response_id => original_id} -> 395 | event = Map.put(event, "id", original_id) 396 | 397 | handler.(event) 398 | 399 | {:noreply, %{state | id_map: Map.delete(state.id_map, response_id)}} 400 | 401 | _ -> 402 | Logger.error( 403 | "Did not find original ID for response: #{response_id}. Discarding response!" 404 | ) 405 | 406 | {:noreply, state} 407 | end 408 | end 409 | 410 | # no id, so must be a notification that we can just forward as is 411 | defp handle_event(%{"jsonrpc" => "2.0"} = event, state, {req, _}) do 412 | req.(event) 413 | 414 | {:noreply, state} 415 | end 416 | 417 | ## other helpers 418 | 419 | defp forward_message(message, endpoint, debug) do 420 | if debug, do: Logger.debug("Forwarding request to server: #{inspect(message)}") 421 | 422 | case Req.post(endpoint, 423 | json: message, 424 | receive_timeout: Application.get_env(:mcp_proxy, :receive_timeout, 60_000) 425 | ) do 426 | {:ok, _} -> 427 | # even when the server replies with a status code that is not in the 200 range 428 | # it might still send a reply on the SSE connection 429 | :ok 430 | 431 | {:error, reason} -> 432 | Logger.error("Failed to forward message #{inspect(message)}:\n#{inspect(reason)}") 433 | 434 | {:reply_error, 435 | %{ 436 | jsonrpc: "2.0", 437 | error: %{ 438 | code: -32011, 439 | message: "Failed to forward request. Reason: #{inspect(reason)}" 440 | } 441 | }} 442 | end 443 | end 444 | 445 | defp random_id! do 446 | :crypto.strong_rand_bytes(8) |> Base.url_encode64(padding: false) 447 | end 448 | 449 | defp disconnected_too_long?(%{max_disconnected_time: seconds, disconnected_since: ts}) 450 | when is_integer(seconds) and is_struct(ts, DateTime) do 451 | DateTime.diff(DateTime.utc_now(), ts, :second) > seconds 452 | end 453 | 454 | defp disconnected_too_long?(_), do: false 455 | 456 | defp reply_disconnected(id) do 457 | IO.puts( 458 | Jason.encode!(%{ 459 | jsonrpc: "2.0", 460 | id: id, 461 | error: %{ 462 | code: -32010, 463 | message: 464 | "Server not connected. The SSE endpoint is currently not available. Please ensure it is running and retry." 465 | } 466 | }) 467 | ) 468 | end 469 | 470 | defp connected_state(state) do 471 | %{state | state: :connected, connect_tries: 0, disconnected_since: nil, buf_mode: :store} 472 | end 473 | end 474 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule McpProxy.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.3.3" 5 | 6 | def project do 7 | [ 8 | app: :mcp_proxy, 9 | version: @version, 10 | elixir: "~> 1.15", 11 | start_permanent: Mix.env() == :prod, 12 | deps: deps(), 13 | package: package(), 14 | description: description(), 15 | escript: escript(), 16 | elixirc_paths: elixirc_paths(Mix.env()), 17 | docs: docs() 18 | ] 19 | end 20 | 21 | defp escript do 22 | [ 23 | main_module: McpProxy, 24 | name: "mcp-proxy", 25 | path: "mcp-proxy" 26 | ] 27 | end 28 | 29 | defp description() do 30 | "An escript for connecting STDIO based MCP clients to HTTP (SSE) based MCP servers." 31 | end 32 | 33 | defp package do 34 | [ 35 | maintainers: ["Steffen Deusch", "José Valim"], 36 | licenses: ["Apache-2.0"], 37 | links: %{ 38 | GitHub: "https://github.com/tidewave-ai/mcp_proxy_elixir" 39 | }, 40 | files: [ 41 | "lib", 42 | "LICENSE", 43 | "mix.exs", 44 | "README.md", 45 | "CHANGELOG.md", 46 | ".formatter.exs" 47 | ] 48 | ] 49 | end 50 | 51 | def application do 52 | [ 53 | extra_applications: [:logger] 54 | ] 55 | end 56 | 57 | defp elixirc_paths(:test), do: ["lib", "test/support"] 58 | defp elixirc_paths(_), do: ["lib"] 59 | 60 | defp deps do 61 | [ 62 | {:req, "~> 0.5"}, 63 | {:jason, "~> 1.4"}, 64 | {:bandit, "~> 1.6", only: :test}, 65 | {:ex_doc, "~> 0.37.3", only: :dev}, 66 | {:makeup_json, "~> 1.0", only: :dev} 67 | ] 68 | end 69 | 70 | defp docs do 71 | [ 72 | api_reference: false, 73 | main: "readme", 74 | source_ref: "v#{@version}", 75 | source_url: "https://github.com/tidewave-ai/mcp_proxy", 76 | extras: ["README.md", "CHANGELOG.md"] 77 | ] 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bandit": {:hex, :bandit, "1.6.11", "2fbadd60c95310eefb4ba7f1e58810aa8956e18c664a3b2029d57edb7d28d410", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.0", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "543f3f06b4721619a1220bed743aa77bf7ecc9c093ba9fab9229ff6b99eacc65"}, 3 | "earmark_parser": {:hex, :earmark_parser, "1.4.44", "f20830dd6b5c77afe2b063777ddbbff09f9759396500cdbe7523efd58d7a339c", [:mix], [], "hexpm", "4778ac752b4701a5599215f7030989c989ffdc4f6df457c5f36938cc2d2a2750"}, 4 | "ex_doc": {:hex, :ex_doc, "0.37.3", "f7816881a443cd77872b7d6118e8a55f547f49903aef8747dbcb345a75b462f9", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "e6aebca7156e7c29b5da4daa17f6361205b2ae5f26e5c7d8ca0d3f7e18972233"}, 5 | "finch": {:hex, :finch, "0.19.0", "c644641491ea854fc5c1bbaef36bfc764e3f08e7185e1f084e35e0672241b76d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.6.2 or ~> 1.7", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc5324ce209125d1e2fa0fcd2634601c52a787aff1cd33ee833664a5af4ea2b6"}, 6 | "hpax": {:hex, :hpax, "1.0.3", "ed67ef51ad4df91e75cc6a1494f851850c0bd98ebc0be6e81b026e765ee535aa", [:mix], [], "hexpm", "8eab6e1cfa8d5918c2ce4ba43588e894af35dbd8e91e6e55c817bca5847df34a"}, 7 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 8 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 9 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 10 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"}, 11 | "makeup_json": {:hex, :makeup_json, "1.0.0", "03886f244d9db4179a9ecfffde5e711480e04e16ef91ca484d2b51ca3251a18f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.1", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "5c8c559e658c7f7e91b96c4b8c40f5912ea0adff44b7afe73e4639d9c3f53b94"}, 12 | "mime": {:hex, :mime, "2.0.6", "8f18486773d9b15f95f4f4f1e39b710045fa1de891fada4516559967276e4dc2", [:mix], [], "hexpm", "c9945363a6b26d747389aac3643f8e0e09d30499a138ad64fe8fd1d13d9b153e"}, 13 | "mint": {:hex, :mint, "1.7.1", "113fdb2b2f3b59e47c7955971854641c61f378549d73e829e1768de90fc1abf1", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "fceba0a4d0f24301ddee3024ae116df1c3f4bb7a563a731f45fdfeb9d39a231b"}, 14 | "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, 15 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, 16 | "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, 17 | "plug": {:hex, :plug, "1.17.0", "a0832e7af4ae0f4819e0c08dd2e7482364937aea6a8a997a679f2cbb7e026b2e", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f6692046652a69a00a5a21d0b7e11fcf401064839d59d6b8787f23af55b1e6bc"}, 18 | "plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"}, 19 | "req": {:hex, :req, "0.5.10", "a3a063eab8b7510785a467f03d30a8d95f66f5c3d9495be3474b61459c54376c", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.17", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "8a604815743f8a2d3b5de0659fa3137fa4b1cffd636ecb69b30b2b9b2c2559be"}, 20 | "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, 21 | "thousand_island": {:hex, :thousand_island, "1.3.12", "590ff651a6d2a59ed7eabea398021749bdc664e2da33e0355e6c64e7e1a2ef93", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "55d0b1c868b513a7225892b8a8af0234d7c8981a51b0740369f3125f7c99a549"}, 22 | "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, 23 | } 24 | -------------------------------------------------------------------------------- /test/mcp_proxy_test.exs: -------------------------------------------------------------------------------- 1 | defmodule McpProxyTest do 2 | use ExUnit.Case, async: false 3 | doctest McpProxy 4 | 5 | import ExUnit.CaptureIO 6 | 7 | alias McpProxy.SSEServer 8 | 9 | setup context do 10 | {result, output} = 11 | with_io(:stderr, fn -> 12 | _server_pid = start_supervised!(SSEServer, restart: :temporary) 13 | port = SSEServer.port() 14 | 15 | parent = self() 16 | 17 | _main_pid = 18 | spawn_link(fn -> 19 | Process.group_leader(self(), parent) 20 | 21 | McpProxy.main( 22 | ["http://localhost:#{port}/sse", "--debug"] ++ (context[:extra_args] || []) 23 | ) 24 | end) 25 | 26 | assert_receive {:io_request, io_pid, reply_as, {:get_line, :unicode, []}} 27 | 28 | send_message(io_pid, reply_as, %{ 29 | jsonrpc: "2.0", 30 | id: "init-1", 31 | method: "initialize", 32 | params: %{ 33 | protocolVersion: "2024-11-05", 34 | capabilities: %{} 35 | } 36 | }) 37 | 38 | assert_receive {:io_request, ^io_pid, reply_as, {:get_line, :unicode, []}} 39 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 1000 40 | send(put_pid, {:io_reply, put_reply_as, :ok}) 41 | 42 | assert %{"id" => "init-1", "result" => init_response} = Jason.decode!(json) 43 | 44 | assert %{"serverInfo" => %{"name" => "Echo MCP Server"}, "tools" => [tool]} = 45 | init_response 46 | 47 | assert tool["name"] == "echo" 48 | 49 | send_message(io_pid, reply_as, %{ 50 | jsonrpc: "2.0", 51 | method: "notifications/initialized" 52 | }) 53 | 54 | assert_receive {:io_request, ^io_pid, reply_as, {:get_line, :unicode, []}} 55 | 56 | %{port: port, io_pid: io_pid, reply_as: reply_as} 57 | end) 58 | 59 | ["Found endpoint: " <> endpoint_url] = Regex.run(~r/Found endpoint: .*/, output) 60 | %{"session_id" => session_id} = URI.new!(endpoint_url).query |> URI.decode_query() 61 | [{sse_pid, _}] = Registry.lookup(McpProxy.SSEServer.Registry, session_id) 62 | 63 | Map.merge(result, %{session_id: session_id, sse_pid: sse_pid}) 64 | end 65 | 66 | test "connects to SSE server running 2024-11-05 protocol", %{io_pid: io_pid, reply_as: reply_as} do 67 | capture_io(:stderr, fn -> 68 | send_message( 69 | io_pid, 70 | reply_as, 71 | %{ 72 | jsonrpc: "2.0", 73 | id: "call-1", 74 | method: "tools/call", 75 | params: %{"name" => "echo", "arguments" => %{"what" => "Hey!"}} 76 | } 77 | ) 78 | 79 | assert_receive {:io_request, ^io_pid, _reply_as, {:get_line, :unicode, []}} 80 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 5000 81 | send(put_pid, {:io_reply, put_reply_as, :ok}) 82 | 83 | assert %{"id" => "call-1", "result" => call_response} = Jason.decode!(json) 84 | assert %{"content" => [%{"text" => "Hey!"}]} = call_response 85 | end) 86 | end 87 | 88 | test "handles server reconnects gracefully", %{ 89 | io_pid: io_pid, 90 | reply_as: reply_as, 91 | port: port 92 | } do 93 | io = 94 | capture_io(:stderr, fn -> 95 | # bye bye, server! 96 | stop_supervised!(SSEServer) 97 | 98 | # now send a client request 99 | send_message( 100 | io_pid, 101 | reply_as, 102 | %{ 103 | jsonrpc: "2.0", 104 | id: "call-1", 105 | method: "tools/call", 106 | params: %{"name" => "echo", "arguments" => %{"what" => "Hey!"}} 107 | } 108 | ) 109 | 110 | # now start the server again 111 | start_supervised!({SSEServer, [port: port]}) 112 | 113 | assert_receive {:io_request, _io_pid, _reply_as, {:get_line, :unicode, []}} 114 | 115 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 5000 116 | send(put_pid, {:io_reply, put_reply_as, :ok}) 117 | 118 | assert %{"id" => "call-1", "result" => call_response} = Jason.decode!(json) 119 | assert %{"content" => [%{"text" => "Hey!"}]} = call_response 120 | end) 121 | 122 | assert io =~ "SSE connection closed. Trying to reconnect" 123 | assert io =~ "Flushing buffer" 124 | end 125 | 126 | @tag extra_args: ["--receive-timeout", "50"] 127 | test "handles receive timeout", %{io_pid: io_pid, reply_as: reply_as} do 128 | capture_io(:stderr, fn -> 129 | send_message( 130 | io_pid, 131 | reply_as, 132 | %{ 133 | jsonrpc: "2.0", 134 | id: "call-1", 135 | method: "tools/call", 136 | params: %{"name" => "sleep", "arguments" => %{"time" => 100}} 137 | } 138 | ) 139 | 140 | assert_receive {:io_request, _io_pid, _reply_as, {:get_line, :unicode, []}} 141 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 100 142 | send(put_pid, {:io_reply, put_reply_as, :ok}) 143 | 144 | assert %{"id" => "call-1", "error" => %{"message" => message}} = Jason.decode!(json) 145 | assert message =~ "Failed to forward request" 146 | 147 | # wait an extra 100 milliseconds for the log about discarding a duplicate response 148 | Process.sleep(100) 149 | end) =~ "Discarding!" 150 | end 151 | 152 | test "ignores notifications while disconnected", %{ 153 | io_pid: io_pid, 154 | reply_as: reply_as, 155 | port: port 156 | } do 157 | io = 158 | capture_io(:stderr, fn -> 159 | # bye bye, server! 160 | stop_supervised!(SSEServer) 161 | 162 | # now send a client request 163 | send_message( 164 | io_pid, 165 | reply_as, 166 | %{ 167 | jsonrpc: "2.0", 168 | method: "notifications/cancelled", 169 | params: %{"reason" => "Error: MCP error -32001: Request timed out", "requestId" => 6} 170 | } 171 | ) 172 | 173 | # now start the server again 174 | start_supervised!({SSEServer, [port: port]}) 175 | 176 | assert_receive {:io_request, io_pid, reply_as, {:get_line, :unicode, []}} 177 | 178 | send_message( 179 | io_pid, 180 | reply_as, 181 | %{ 182 | jsonrpc: "2.0", 183 | id: "call-1", 184 | method: "tools/call", 185 | params: %{"name" => "echo", "arguments" => %{"what" => "Hey!"}} 186 | } 187 | ) 188 | 189 | assert_receive {:io_request, _io_pid, _reply_as, {:get_line, :unicode, []}} 190 | 191 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 5000 192 | send(put_pid, {:io_reply, put_reply_as, :ok}) 193 | 194 | assert %{"id" => "call-1", "result" => call_response} = Jason.decode!(json) 195 | assert %{"content" => [%{"text" => "Hey!"}]} = call_response 196 | end) 197 | 198 | assert io =~ "Ignoring notification while disconnected" 199 | end 200 | 201 | test "ignores comments", %{ 202 | io_pid: io_pid, 203 | reply_as: reply_as, 204 | sse_pid: sse_pid 205 | } do 206 | io = 207 | capture_io(:stderr, fn -> 208 | # send a comment 209 | GenServer.cast(sse_pid, {:send_sse, ": hello world"}) 210 | 211 | send_message( 212 | io_pid, 213 | reply_as, 214 | %{ 215 | jsonrpc: "2.0", 216 | id: "call-1", 217 | method: "tools/call", 218 | params: %{"name" => "echo", "arguments" => %{"what" => "Hey!"}} 219 | } 220 | ) 221 | 222 | assert_receive {:io_request, _io_pid, _reply_as, {:get_line, :unicode, []}} 223 | 224 | assert_receive {:io_request, put_pid, put_reply_as, {:put_chars, :unicode, json}}, 5000 225 | send(put_pid, {:io_reply, put_reply_as, :ok}) 226 | 227 | assert %{"id" => "call-1", "result" => call_response} = Jason.decode!(json) 228 | assert %{"content" => [%{"text" => "Hey!"}]} = call_response 229 | end) 230 | 231 | assert io =~ "Ignoring SSE line" 232 | end 233 | 234 | defp send_message(io_pid, reply_as, json) do 235 | send(io_pid, {:io_reply, reply_as, Jason.encode_to_iodata!(json)}) 236 | end 237 | end 238 | -------------------------------------------------------------------------------- /test/support/sse_server.ex: -------------------------------------------------------------------------------- 1 | defmodule McpProxy.SSEServer do 2 | use Supervisor 3 | 4 | def start_link(init_arg) do 5 | Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__) 6 | end 7 | 8 | def init(opts) do 9 | children = [ 10 | {Registry, keys: :unique, name: __MODULE__.Registry}, 11 | {Bandit, 12 | plug: __MODULE__.Router, 13 | port: opts[:port] || 0, 14 | thousand_island_options: [ 15 | shutdown_timeout: 10, 16 | supervisor_options: [name: {:via, Registry, {__MODULE__.Registry, Bandit}}] 17 | ]} 18 | ] 19 | 20 | Supervisor.init(children, strategy: :one_for_one) 21 | end 22 | 23 | def port do 24 | [{pid, _}] = Registry.lookup(__MODULE__.Registry, Bandit) 25 | {:ok, {_, port}} = ThousandIsland.listener_info(pid) 26 | port 27 | end 28 | 29 | defmodule Router do 30 | use Plug.Router 31 | 32 | plug(:match) 33 | 34 | plug(Plug.Parsers, 35 | parsers: [:json], 36 | pass: ["application/json"], 37 | json_decoder: Jason 38 | ) 39 | 40 | plug(:dispatch) 41 | 42 | get "/sse" do 43 | session_id = :crypto.strong_rand_bytes(8) |> Base.url_encode64() 44 | {:ok, _} = Registry.register(McpProxy.SSEServer.Registry, session_id, nil) 45 | 46 | conn 47 | |> put_resp_header("cache-control", "no-cache") 48 | |> put_resp_header("connection", "keep-alive") 49 | |> put_resp_header("content-type", "text/event-stream; charset=utf-8") 50 | |> send_chunked(200) 51 | |> tap(fn conn -> 52 | # initial endpoint message 53 | endpoint = "#{conn.scheme}://#{conn.host}:#{conn.port}/message?session_id=#{session_id}" 54 | 55 | case chunk(conn, "event: endpoint\ndata: #{endpoint}\n\n") do 56 | {:ok, conn} -> 57 | try do 58 | :gen_server.enter_loop(McpProxy.SSEServer.Echo, [], %{ 59 | session_id: session_id, 60 | conn: conn 61 | }) 62 | catch 63 | :exit, :normal -> conn 64 | :exit, :shutdown -> conn 65 | after 66 | send(self(), {:plug_conn, :sent}) 67 | end 68 | 69 | {:error, :closed} -> 70 | conn 71 | end 72 | end) 73 | end 74 | 75 | post "/message" do 76 | with %{query_params: %{"session_id" => session_id}} <- conn, 77 | [{pid, _}] <- Registry.lookup(McpProxy.SSEServer.Registry, session_id) do 78 | GenServer.call(pid, {:request, conn.body_params}) 79 | 80 | conn 81 | |> put_resp_content_type("application/json") 82 | |> send_resp(202, Jason.encode!(%{status: "ok"})) 83 | end 84 | end 85 | end 86 | 87 | defmodule Echo do 88 | use GenServer 89 | 90 | @impl GenServer 91 | def init(_) do 92 | {:ok, nil} 93 | end 94 | 95 | @impl GenServer 96 | def handle_call({:request, message}, _from, state) do 97 | result = handle_message(message) 98 | 99 | if result do 100 | case Plug.Conn.chunk(state.conn, ["event: message\ndata: ", result]) do 101 | {:ok, conn} -> {:reply, :ok, %{state | conn: conn}} 102 | {:error, :closed} -> {:stop, :shutdown, state} 103 | end 104 | else 105 | {:reply, :ok, state} 106 | end 107 | end 108 | 109 | @impl GenServer 110 | def handle_cast({:send_sse, line}, state) do 111 | case Plug.Conn.chunk(state.conn, line) do 112 | {:ok, conn} -> {:noreply, %{state | conn: conn}} 113 | {:error, :closed} -> {:stop, :shutdown, state} 114 | end 115 | end 116 | 117 | @impl GenServer 118 | def handle_info(_other, state) do 119 | {:noreply, state} 120 | end 121 | 122 | defp handle_message(%{"id" => request_id, "method" => "initialize"}) do 123 | Jason.encode_to_iodata!(%{ 124 | jsonrpc: "2.0", 125 | id: request_id, 126 | result: %{ 127 | protocolVersion: "2024-11-05", 128 | capabilities: %{ 129 | tools: %{ 130 | listChanged: false 131 | } 132 | }, 133 | serverInfo: %{ 134 | name: "Echo MCP Server", 135 | version: "1.0.0" 136 | }, 137 | tools: [ 138 | %{ 139 | name: "echo", 140 | description: "Echo!", 141 | inputSchema: %{ 142 | type: "object", 143 | required: ["what"], 144 | properties: %{ 145 | what: %{ 146 | type: "string", 147 | description: "The string to echo" 148 | } 149 | } 150 | } 151 | } 152 | ] 153 | } 154 | }) 155 | end 156 | 157 | defp handle_message(%{"method" => "notifications/initialized"}), do: nil 158 | 159 | defp handle_message(%{"id" => request_id, "method" => "ping"}) do 160 | Jason.encode_to_iodata!(%{jsonrpc: 2.0, id: request_id, result: %{}}) 161 | end 162 | 163 | defp handle_message(%{ 164 | "id" => request_id, 165 | "method" => "tools/call", 166 | "params" => %{"name" => "echo", "arguments" => %{"what" => what}} 167 | }) do 168 | Jason.encode_to_iodata!(%{ 169 | jsonrpc: "2.0", 170 | id: request_id, 171 | result: %{content: [%{text: what}]} 172 | }) 173 | end 174 | 175 | defp handle_message(%{ 176 | "id" => request_id, 177 | "method" => "tools/call", 178 | "params" => %{"name" => "sleep", "arguments" => %{"time" => time}} 179 | }) do 180 | Process.sleep(time) 181 | 182 | Jason.encode_to_iodata!(%{ 183 | jsonrpc: "2.0", 184 | id: request_id, 185 | result: %{content: [%{text: "Ok"}]} 186 | }) 187 | end 188 | 189 | defp handle_message(%{"id" => id, "method" => other} = _message) do 190 | Jason.encode_to_iodata!(%{ 191 | jsonrpc: "2.0", 192 | id: id, 193 | error: %{ 194 | code: -32601, 195 | message: "Method not found", 196 | data: %{ 197 | name: other 198 | } 199 | } 200 | }) 201 | end 202 | end 203 | end 204 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------