From a514c73b6813d334bfad958d65d538fe89bc9825 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sat, 14 Nov 2026 16:35:55 -0500 Subject: [PATCH] refactor(mcp): rewrite MCP natives in Gleam Move credentials, the catalogue cache, OAuth, settings validation, transport construction, and call dispatch from Erlang into Gleam modules (secrets, catalogue, oauth, servers, dispatch). albedo_mcp_credentials.erl, albedo_mcp_catalogue.erl, and albedo_mcp_oauth.erl are gone. albedo_mcp.erl keeps the connection lifecycle: owned starts, adoption, connectors, dials, refreshes, the watcher, timed calls, and bounded close. albedo_mcp_stdio.erl keeps the port and gains the OS lookups a transport needs (daemon variables, executables, launcher path, port env list). New SDK modules bind the OTP and settings-store calls extensions cannot: term_codec, settings_documents, file_status, and log. --- robot-docs/extensions.md | 13 + robot-docs/mcp.md | 30 +- .../harness/extensions/mcp/albedo_mcp.erl | 451 +----- .../extensions/mcp/albedo_mcp_catalogue.erl | 138 -- .../extensions/mcp/albedo_mcp_credentials.erl | 27 - .../extensions/mcp/albedo_mcp_oauth.erl | 841 ---------- .../extensions/mcp/albedo_mcp_stdio.erl | 54 +- .../harness/extensions/mcp/catalogue.gleam | 281 +++- .../harness/extensions/mcp/dispatch.gleam | 125 ++ .../harness/extensions/mcp/extension.gleam | 10 +- src/albedo/harness/extensions/mcp/oauth.gleam | 1389 +++++++++++++++++ .../harness/extensions/mcp/preparation.gleam | 38 +- .../harness/extensions/mcp/secrets.gleam | 55 + .../harness/extensions/mcp/servers.gleam | 542 +++++++ .../harness/extensions/mcp/sign_in.gleam | 50 +- src/albedo/harness/sdk/file_status.gleam | 64 + src/albedo/harness/sdk/log.gleam | 10 + .../harness/sdk/settings_documents.gleam | 67 + src/albedo/harness/sdk/term_codec.gleam | 37 + .../albedo_mcp_catalogue_test_support.erl | 15 +- .../albedo_mcp_ownership_test_support.erl | 11 +- test/harness/mcp_credentials_test.gleam | 6 +- test/harness/mcp_url_test.gleam | 6 +- 23 files changed, 2745 insertions(+), 1515 deletions(-) delete mode 100644 src/albedo/harness/extensions/mcp/albedo_mcp_catalogue.erl delete mode 100644 src/albedo/harness/extensions/mcp/albedo_mcp_credentials.erl delete mode 100644 src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl create mode 100644 src/albedo/harness/extensions/mcp/dispatch.gleam create mode 100644 src/albedo/harness/extensions/mcp/oauth.gleam create mode 100644 src/albedo/harness/extensions/mcp/secrets.gleam create mode 100644 src/albedo/harness/extensions/mcp/servers.gleam create mode 100644 src/albedo/harness/sdk/file_status.gleam create mode 100644 src/albedo/harness/sdk/log.gleam create mode 100644 src/albedo/harness/sdk/settings_documents.gleam create mode 100644 src/albedo/harness/sdk/term_codec.gleam diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index e8f952453..246a4e2ad 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -174,6 +174,19 @@ The SDK also provides these helpers. range reads close descriptors on every outcome. `with_lock` serializes a complete cache update within this daemon; it is separate from credential transactions and does not coordinate other OS processes. +- [`sdk/file_status`](../src/albedo/harness/sdk/file_status.gleam): The kind, + size, and permission bits of a path without following a final symbolic link, + for checks that a secret file is private before reading it. +- [`sdk/settings_documents`](../src/albedo/harness/sdk/settings_documents.gleam): + Whole settings documents such as `creds.json`, read and committed as a group + through the settings store. Hold `with_lock` across a read and the commit that + depends on it. `mcp_secrets` reads the `mcp` section of `creds.json`. +- [`sdk/term_codec`](../src/albedo/harness/sdk/term_codec.gleam): The Erlang + external term format for caches and fingerprints that earlier daemons wrote. + `decode_safe` refuses bytes that would create unknown atoms or functions. Use + JSON for new persisted data. +- [`sdk/log`](../src/albedo/harness/sdk/log.gleam): Warnings for the daemon's + log. Never include secrets or tokens. - [`sdk/subprocess`](../src/albedo/harness/sdk/subprocess.gleam): Credential helpers with bounded stdout and timeouts. - [`sdk/helper`](../src/albedo/harness/sdk/helper.gleam): Python helper diff --git a/robot-docs/mcp.md b/robot-docs/mcp.md index aedaf6ea3..17b0242ae 100644 --- a/robot-docs/mcp.md +++ b/robot-docs/mcp.md @@ -22,6 +22,13 @@ The daemon's `mcp` settings group saves definitions in `extensions.json` and secrets in `creds.json`. It reaches the configured extension's checks through its `McpServersPlugin`, described in [plugins](plugins.md#mcp-settings-and-editor-probes). +[`servers.gleam`](../src/albedo/harness/extensions/mcp/servers.gleam) owns +`validate_settings`, server names, the URL rule, and the client transport. +Validation never resolves environment references. A transport resolves them when +it is built. +[`secrets.gleam`](../src/albedo/harness/extensions/mcp/secrets.gleam) reads a +server's `creds.json` entry. It refuses a `creds.json` that is not a regular +file, is larger than 1 MiB, or grants group or other permissions. [`albedo_settings_http`](../src/albedo/daemon/albedo_settings_http.erl) calls `validate` for each changed server and `check` when `validate_connection` is true. It calls `signed_out` when a patch sets `oauth` to null. These checks run @@ -34,6 +41,11 @@ writes the credential into the server's `creds.json` entry and keeps the registration of an earlier sign-in. Its exchange checks the `issuer` on the `oauth.Grant` it receives against the authorization server's issuer. See [sign-in](auth.md#sign-in). +[`oauth.gleam`](../src/albedo/harness/extensions/mcp/oauth.gleam) owns +discovery, client registration, the token exchange, and the token a request +sends. Refreshes of one server are single-flight within the daemon. Record +updates hold the settings lock through +[`sdk/settings_documents`](../src/albedo/harness/sdk/settings_documents.gleam). ## Tools and lifecycle @@ -51,6 +63,9 @@ interrupted call may have had effects, so inspect those effects before retrying. A server-reported error appears in `isError`. A host failure raises `McpError`. See [extension.gleam](../src/albedo/harness/extensions/mcp/extension.gleam) and [mcp.py](../priv/python/albedo_plugins/mcp.py). +[`dispatch.gleam`](../src/albedo/harness/extensions/mcp/dispatch.gleam) builds +each call's request and refuses a result larger than 4 MiB. The native call +worker in `albedo_mcp.erl` owns its deadline. ## Catalogue policy and cache @@ -72,12 +87,19 @@ validates `x-mcp-header` annotations and converts call arguments to header values. HTTP discovery warns and excludes a tool with invalid annotations. Stdio discovery retains that tool without mirrored headers. -[`albedo_mcp_catalogue.erl`](../src/albedo/harness/extensions/mcp/albedo_mcp_catalogue.erl) -reads and writes the existing version 2 external-term cache, converting its -native maps at that boundary. Keep that saved shape compatible with existing -catalogues. Native monitor, adoption, and cleanup mechanisms remain in +`catalogue.encode` and `catalogue.saved` write and read the existing version 2 +external-term cache through +[`sdk/term_codec`](../src/albedo/harness/sdk/term_codec.gleam). The cache holds +atom-keyed maps, not Gleam records. Keep that saved shape compatible with +existing catalogues. `servers.fingerprint` keys each saved catalogue, so keep +its term encoding stable as well. Native monitor, adoption, and cleanup +mechanisms remain in [`albedo_mcp.erl`](../src/albedo/harness/extensions/mcp/albedo_mcp.erl) and [`client.gleam`](../src/albedo/harness/extensions/mcp/client.gleam). +[`albedo_mcp_stdio.erl`](../src/albedo/harness/extensions/mcp/albedo_mcp_stdio.erl) +owns the stdio port and the OS lookups a transport needs: daemon variables, +executables, and the launcher path. A stdio server's port unsets every daemon +variable except a short safe list, then sets the server's own. ## Preparation and connection ownership diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp.erl b/src/albedo/harness/extensions/mcp/albedo_mcp.erl index 8869076d2..db7dd164b 100644 --- a/src/albedo/harness/extensions/mcp/albedo_mcp.erl +++ b/src/albedo/harness/extensions/mcp/albedo_mcp.erl @@ -14,36 +14,28 @@ closer/1, call/3, close/1, - adopt/1, - url_allowed/1, - validate_settings/3 + adopt/1 ]). -export([ - fingerprint/2, - preparation_saved/1, preparation_connect/4, preparation_save/5, preparation_join/5, preparation_configured_join/4, - preparation_selected/3, close_joined/1 ]). -define(PREPARATION, 'albedo@harness@extensions@mcp@preparation'). -define(CATALOGUE, 'albedo@harness@extensions@mcp@catalogue'). --define(PARAM_HEADERS, 'albedo@harness@extensions@mcp@param_headers'). +-define(DISPATCH, 'albedo@harness@extensions@mcp@dispatch'). -define(CONNECTOR, 'albedo@harness@extensions@mcp@connector'). -define(CLIENT, 'albedo@harness@extensions@mcp@client'). +-define(SERVERS, 'albedo@harness@extensions@mcp@servers'). --define(DEFAULT_STARTUP_MS, 20000). --define(DEFAULT_CALL_MS, 60000). -define(CLOSE_MS, 2500). --define(DEFAULT_RETRY_MS, 30000). -define(WATCHER, 'albedo@harness@extensions@mcp@watcher'). --define(SAFE_ENV, ["HOME", "PATH", "TMPDIR", "TEMP", "TMP", "SystemRoot", "WINDIR"]). %% `Lookup(Name, Fingerprint)` answers a server's last saved catalogue and %% `Save(Name, Fingerprint, Catalogue)` replaces it. A server with a saved @@ -51,11 +43,7 @@ %% without connects here, since nothing else can say what it offers. prepare(ConfigJson, Ledger, Session, Lookup, Save, Preparer, Runtime) -> try - Config = json:decode(ConfigJson), - Servers = maps:get(<<"servers">>, Config, #{}), - true = is_map(Servers), - Retry = positive_ms(maps:get(<<"retryMs">>, Config, ?DEFAULT_RETRY_MS)), - Candidates = lists:sort(maps:to_list(Servers)), + {ok, {Candidates, Retry}} = ?SERVERS:configured_candidates(ConfigJson), Selection = case Candidates of [] -> none; @@ -78,15 +66,13 @@ prepare(ConfigJson, Ledger, Session, Lookup, Save, Preparer, Runtime) -> %% `mcp` binding reaches them through the editor-mcp extension's routes. prepare_overlay(ServersJson, Workspace, Lookup, Save, Preparer, Runtime) -> try - Servers = json:decode(ServersJson), - true = is_list(Servers), - Candidates = [overlay_candidate(Server, Workspace) || Server <- Servers], + {ok, Candidates} = ?SERVERS:overlay_candidates(ServersJson, Workspace), case join_overlay(Candidates, [], {Lookup, Save}, {Preparer, Runtime}) of {ok, Joined} -> finish( Joined, [], - ?DEFAULT_RETRY_MS, + ?SERVERS:default_retry(), <<"The editor's MCP servers">>, {Preparer, Runtime} ); @@ -97,43 +83,17 @@ prepare_overlay(ServersJson, Workspace, Lookup, Save, Preparer, Runtime) -> _:_ -> {error, <<"editor MCP servers are invalid">>} end. -overlay_candidate( - #{ - <<"name">> := Name, - <<"command">> := Command, - <<"args">> := Args, - <<"env">> := Env - }, - Workspace -) when - is_binary(Name), is_binary(Command), is_list(Args), is_list(Env) --> - Literal = maps:from_list([ - {N, V} - || #{<<"name">> := N, <<"value">> := V} <- Env, - is_binary(N), - is_binary(V) - ]), - Config = #{ - <<"type">> => <<"stdio">>, - <<"command">> => Command, - <<"args">> => Args, - <<"cwd">> => Workspace - }, - {Name, Config, #{<<"env">> => Literal}}. - %% Probe with no saved catalogue or global writes. A rejected candidate owns %% no cache entries, and every connection closes before returning its values. probe_overlay(ServersJson, Workspace) -> try - Candidates = [overlay_candidate(Server, Workspace) || Server <- json:decode(ServersJson)], + {ok, Candidates} = ?SERVERS:overlay_candidates(ServersJson, Workspace), Cache = {fun(_, _) -> none end, fun(_, _, _) -> nil end}, case join_overlay(Candidates, [], Cache, self()) of {ok, Joined} -> try {ok, [ - {Name, fingerprint(Config, Secrets), - albedo_mcp_catalogue:encode_catalogue(Catalogue)} + {Name, ?SERVERS:fingerprint(Config, Secrets), ?CATALOGUE:encode(Catalogue)} || {Name, Config, Secrets, Catalogue, _} <- Joined ]} after @@ -163,23 +123,6 @@ open_servers(Candidates, Preferences, Retry, Cache, Owners) -> Error end. -preparation_selected(Name, Config, Preferences) -> - try - case - { - maps:get(<<"enabled">>, Config, true), - 'albedo@harness@capabilities':enabled(Preferences, <<"mcp">>, Name) - } - of - {true, {ok, true}} -> {ok, true}; - {false, _} -> {ok, false}; - {_, {ok, false}} -> {ok, false}; - {_, {error, Reason}} -> {error, Reason} - end - catch - _:_ -> {error, <<"MCP configuration is invalid">>} - end. - preparation_configured_join(Name, Config, Cache, Owners) -> try typed_join(join(Name, Config, Cache, Owners)) @@ -190,11 +133,11 @@ preparation_configured_join(Name, Config, Cache, Owners) -> %% A joined server is its catalogue and how its connector starts: from the %% client this preparation connected, or by dialling to check a saved one. join(Name, Config, {Lookup, Save}, Owners) when is_binary(Name), is_map(Config) -> - case valid_name(Name) of + case ?SERVERS:valid_name(Name) of false -> {error, <<"MCP server name is invalid">>}; true -> - case albedo_mcp_credentials:server(Name) of + case 'albedo@harness@extensions@mcp@secrets':server(Name) of {ok, Secrets} -> join_with_secrets(Name, Config, Secrets, {Lookup, Save}, Owners); Error -> @@ -219,12 +162,6 @@ preparation_join(Name, Config, Secrets, Cache, Owners) -> _:_ -> {error, {invalid, <<"MCP configuration is invalid">>}} end. -preparation_saved(Value) -> - case albedo_mcp_catalogue:saved(Value) of - {ok, Catalogue} -> {some, Catalogue}; - none -> none - end. - preparation_connect(Name, Config, Secrets, Owners) -> case connect(Name, Config, Secrets, Owners) of {ok, Server, Catalogue} -> {ok, {Server, Catalogue}}; @@ -237,7 +174,7 @@ typed_join({needs_sign_in, _, Reason}) -> {error, {needs_sign_in, Reason}}; typed_join({error, Reason}) -> {error, {invalid, Reason}}. preparation_save(Server, Name, Fingerprint, Catalogue, Save) -> - try Save(Name, Fingerprint, albedo_mcp_catalogue:encode_catalogue(Catalogue)) of + try Save(Name, Fingerprint, ?CATALOGUE:encode(Catalogue)) of _ -> {ok, nil} catch _:_ -> @@ -291,11 +228,11 @@ finish_links(Joined, Watcher, Owners, Servers) -> end. open_server(Name, Config) when is_binary(Name), is_map(Config) -> - case valid_name(Name) of + case ?SERVERS:valid_name(Name) of false -> {error, <<"MCP server name is invalid">>}; true -> - case albedo_mcp_credentials:server(Name) of + case 'albedo@harness@extensions@mcp@secrets':server(Name) of {ok, Secrets} -> open_server_with_secrets(Name, Config, Secrets); Error -> Error end @@ -308,9 +245,8 @@ open_server_with_secrets(Name, Config, Secrets) -> open_server_with_secrets(Name, Config, Secrets, Owner) -> try - Startup = positive_ms(maps:get(<<"startupTimeoutMs">>, Config, ?DEFAULT_STARTUP_MS)), - Call = positive_ms(maps:get(<<"callTimeoutMs">>, Config, ?DEFAULT_CALL_MS)), - Transport = transport(Name, Config, Secrets), + {ok, {Startup, Call}} = ?SERVERS:timeouts(Config), + {ok, Transport} = ?SERVERS:transport(Name, Config, Secrets), Started = case Owner of {Preparer, Runtime} -> ?CLIENT:start_owned(Transport, Startup, Preparer, Runtime); @@ -338,7 +274,7 @@ open_server_with_secrets(Name, Config, Secrets, Owner) -> connect(Name, Config, Secrets, Owner) -> case open_server_with_secrets(Name, Config, Secrets, Owner) of {ok, Server} -> - case albedo_mcp_catalogue:discover(Server) of + case discover(Server) of {ok, Ops, Summary} -> {ok, Server, {Ops, Summary}}; {error, _} -> @@ -349,180 +285,12 @@ connect(Name, Config, Secrets, Owner) -> Unavailable end. -%% Names one server's configuration and credentials, so a saved catalogue -%% is only trusted for the setup that produced it. -%% A sign-in's tokens change on every refresh, so they are left out, and so is -%% the `tools` class, which changes how a catalogue is shown, not what it is. -fingerprint(Config, Secrets) -> - Stable = maps:remove(<<"oauth">>, Secrets), - Server = maps:remove(<<"tools">>, Config), - binary:encode_hex( - crypto:hash(sha256, term_to_binary({Server, Stable}, [deterministic])), lowercase - ). - -%% The client's transport: an https server is reached through the provider -%% transport, verified against albedo_trust's roots. An HTTP server without -%% an authorization header of its own may sign in with OAuth. -transport(Name, #{<<"type">> := <<"http">>, <<"url">> := Url} = Config, Secrets) when - is_binary(Url), byte_size(Url) > 0 --> - case url_allowed(Url) of - true -> ok; - false -> erlang:error(unsafe_url) - end, - Headers = http_headers(Config, Secrets), - Auth = - case - lists:keymember(<<"authorization">>, 1, [{string:lowercase(K), V} || {K, V} <- Headers]) - of - true -> none; - false -> {some, oauth(Name, Url)} - end, - {http, Url, Headers, Auth}; -transport(_, #{<<"type">> := <<"stdio">>, <<"command">> := Command} = Config, Secrets) when - is_binary(Command), byte_size(Command) > 0 --> - Args = string_list(maps:get(<<"args">>, Config, [])), - Cwd = optional_binary(maps:get(<<"cwd">>, Config, null)), - {stdio, executable(<<"python3">>), [launcher(), Cwd, executable(Command) | Args], - scoped_env(maps:get(<<"env">>, Config, #{}), maps:get(<<"env">>, Secrets, #{}))}; -transport(_, _, _) -> - erlang:error(invalid_transport). - -%% The client.Auth for one server's OAuth sign-in in this daemon's home. -oauth(Name, Url) -> - Home = albedo_extension_settings:home(), - {auth, fun(Refused) -> albedo_mcp_oauth:access(Home, Name, Url, Refused) end, fun( - Status, Challenge - ) -> - albedo_mcp_oauth:challenged(Home, Name, Url, Status, Challenge) - end}. - -url_allowed(Url) -> - try - Parsed = uri_string:parse(Url), - Scheme = maps:get(scheme, Parsed, undefined), - Host = maps:get(host, Parsed, <<>>), - (Scheme =:= <<"https">> orelse Scheme =:= <<"http">>) andalso - is_binary(Host) andalso Host =/= <<>> andalso - maps:get(userinfo, Parsed, undefined) =:= undefined andalso - maps:get(fragment, Parsed, undefined) =:= undefined - catch - _:_ -> false - end. - -http_headers(Config, Secrets) -> - Raw = maps:get(<<"headers">>, Config, #{}), - true = is_map(Raw), - Resolved = maps:fold( - fun(Name, Ref, Acc) -> - set_header(Name, env_reference(Ref), Acc) - end, - [], - Raw - ), - Saved = maps:get(<<"headers">>, Secrets, #{}), - true = is_map(Saved), - SavedHeaders = maps:fold(fun set_header/3, Resolved, Saved), - case - { - maps:get(<<"bearerTokenEnvVar">>, Config, null), - maps:get(<<"bearerToken">>, Secrets, null) - } - of - {null, null} -> - SavedHeaders; - {Name, null} when is_binary(Name) -> with_bearer(required_env(Name), SavedHeaders); - {null, Token} when is_binary(Token), byte_size(Token) > 0 -> - with_bearer(Token, SavedHeaders); - _ -> - erlang:error(invalid_auth) - end. - -with_bearer(Token, Headers) -> - set_header(<<"authorization">>, <<"Bearer ", Token/binary>>, Headers). - -set_header(Name, Value, Headers) when is_binary(Name), is_binary(Value) -> - true = valid_header(Name), - false = contains_newline(Value), - [{Name, Value} | lists:keydelete(Name, 1, Headers)]. - -valid_header(Name) -> - re:run(Name, <<"^[!#$%&'*+.^_`|~0-9A-Za-z-]+$">>, [{capture, none}]) =:= match. -contains_newline(Value) -> - binary:match(Value, [<<"\n">>, <<"\n">>]) =/= nomatch. - -scoped_env(Raw, Secrets) when is_map(Raw), is_map(Secrets) -> - Added = maps:fold( - fun(Target, Ref, Acc) when is_binary(Target) -> - [{binary_to_list(Target), binary_to_list(env_reference(Ref))} | Acc] - end, - [], - Raw - ), - Saved = maps:fold( - fun(Target, Value, Acc) when - is_binary(Target), is_binary(Value) - -> - true = valid_env_name(Target), - [{binary_to_list(Target), binary_to_list(Value)} | Acc] - end, - [], - Secrets - ), - %% A port applies its env list in order, and a later {Name, false} unsets a - %% name an earlier entry set. A server given the daemon's own variable name - %% is the normal case, and that name is in the removal list: removals go - %% first, and never name a variable this server was given. - Given = [Name || {Name, _} <- Added ++ Saved], - Removed = [ - {Name, false} - || Entry <- os:env(), - Name <- [env_name(Entry)], - not lists:member(Name, ?SAFE_ENV), - not lists:member(Name, Given) - ], - Removed ++ Added ++ Saved; -scoped_env(_, _) -> - erlang:error(invalid_env). - -valid_env_name(Name) -> - re:run(Name, <<"^[A-Za-z_][A-Za-z_0-9]*$">>, [{capture, none}]) =:= match. - -env_name({Name, _}) when is_list(Name) -> Name; -env_name(Entry) when is_list(Entry) -> hd(string:split(Entry, "=", leading)). - -env_reference(#{<<"env">> := Name} = Ref) when map_size(Ref) =:= 1, is_binary(Name) -> - required_env(Name); -env_reference(Value) when is_binary(Value) -> Value; -env_reference(_) -> - erlang:error(invalid_env_reference). - -required_env(Name) -> - case os:getenv(binary_to_list(Name)) of - false -> erlang:error(missing_environment); - Value -> unicode:characters_to_binary(Value) - end. - -launcher() -> - case albedo_priv:dir() of - {error, _} -> erlang:error(no_priv_dir); - Dir -> unicode:characters_to_binary(filename:join([Dir, "python", "mcp_stdio.py"])) - end. - -executable(Command) -> - Value = binary_to_list(Command), - case filename:pathtype(Value) of - absolute -> - case filelib:is_regular(Value) of - true -> Command; - false -> erlang:error(no_executable) - end; - _ -> - case os:find_executable(Value) of - false -> erlang:error(no_executable); - Path -> unicode:characters_to_binary(Path) - end +%% Discovery through the catalogue's lifecycle entrypoint, which the +%% ownership tests instrument. +discover(#{name := Name, client := Client, call_timeout := Timeout, config := Config}) -> + case ?CATALOGUE:discover_guarded(Name, Client, Timeout, Config) of + {ok, {Operations, Summary}} -> {ok, Operations, Summary}; + {error, nil} -> {error, discovery_failed} end. definitions(#{operations := Operations}) -> @@ -554,39 +322,32 @@ call(#{servers := Servers, operations := Operations}, Advertised, ArgumentsJson) {ok, Server} -> case timed_dispatch(Operation, Server, Arguments) of {ok, Value} -> - encode_result(Value); + ?DISPATCH:encode_result(Value); {error, timeout} -> {error, <<"MCP request timed out; outcome unknown. Inspect effects before any retry.">>}; {error, {unauthorized, Reason}} -> - {error, needs_sign_in(maps:get(name, Link), Reason)}; + {error, ?DISPATCH:needs_sign_in(maps:get(name, Link), Reason)}; {error, _} -> {error, <<"MCP request failed; outcome unknown. Inspect effects before any retry.">>} end; {needs_sign_in, Reason} -> - {error, needs_sign_in(maps:get(name, Link), Reason)}; + {error, ?DISPATCH:needs_sign_in(maps:get(name, Link), Reason)}; unavailable -> - {error, unavailable(maps:get(name, Link))} + {error, ?DISPATCH:unavailable(maps:get(name, Link))} end catch error:not_found -> {error, <<"MCP tool is unavailable">>}; _:_ -> {error, <<"MCP request failed before dispatch">>} end. -encode_result(Value) -> - Encoded = iolist_to_binary(json:encode(Value)), - case byte_size(Encoded) =< 4194304 of - true -> {ok, Encoded}; - false -> {error, <<"MCP result exceeded the safe output limit">>} - end. - timed_dispatch({operation, _, _, _, _, Timeout, _, _, _} = Operation, Server, Arguments) -> Parent = self(), {Worker, Monitor} = spawn_monitor(fun() -> Result = try - dispatch(Operation, Server, Arguments) + ?DISPATCH:dispatch(Operation, maps:get(client, Server), Arguments) catch _:_ -> {error, transport_lost} end, @@ -608,30 +369,6 @@ timed_dispatch({operation, _, _, _, _, Timeout, _, _, _} = Operation, Server, Ar {error, timeout} end. -dispatch( - {operation, _, _, tool, Raw, Timeout, _, _, ParamHeaders}, #{client := Client}, Arguments -) -> - Params = iolist_to_binary(json:encode(#{<<"name">> => Raw, <<"arguments">> => Arguments})), - Headers = ?PARAM_HEADERS:values(ParamHeaders, Arguments), - ?CLIENT:request_with(Client, <<"tools/call">>, Params, Headers, Timeout); -dispatch({operation, _, _, resource, _, Timeout, _, _, _}, Server, #{<<"uri">> := Uri}) when - is_binary(Uri) --> - request(Server, <<"resources/read">>, #{<<"uri">> => Uri}, Timeout); -dispatch({operation, _, _, prompt, _, Timeout, _, _, _}, Server, #{<<"name">> := Name} = Args) when - is_binary(Name) --> - PromptArgs = maps:get(<<"arguments">>, Args, #{}), - true = is_map(PromptArgs), - request( - Server, <<"prompts/get">>, #{<<"name">> => Name, <<"arguments">> => PromptArgs}, Timeout - ); -dispatch(_, _, _) -> - {error, invalid_arguments}. - -request(#{client := Client}, Method, Params, Timeout) -> - ?CLIENT:request(Client, Method, iolist_to_binary(json:encode(Params)), Timeout). - find(Key, Name, Items) -> case lists:search(fun(Item) -> maps:get(Key, Item) =:= Name end, Items) of {value, Item} -> Item; @@ -740,9 +477,8 @@ stop_owned(_) -> ok. %% changed is discovered again; either saves and reports a catalogue that %% changed so the watcher can refresh the session. link(Name, Config, Secrets, Catalogue, Start, Watcher, Owners) -> - Wait = - positive_ms(maps:get(<<"startupTimeoutMs">>, Config, ?DEFAULT_STARTUP_MS)) + - positive_ms(maps:get(<<"callTimeoutMs">>, Config, ?DEFAULT_CALL_MS)), + {ok, {Startup, Call}} = ?SERVERS:timeouts(Config), + Wait = Startup + Call, Connector = start_owned( Owners, fun() -> @@ -830,11 +566,11 @@ start_refresh( {Pid, Monitor} = spawn_opt( fun() -> Found = - case albedo_mcp_catalogue:discover(Server) of + case discover(Server) of {ok, Ops, Summary} when {Ops, Summary} =:= Expected -> none; {ok, Ops, Summary} -> Save( - Name, Fingerprint, albedo_mcp_catalogue:encode_catalogue({Ops, Summary}) + Name, Fingerprint, ?CATALOGUE:encode({Ops, Summary}) ), Watcher ! {changed, Name}, {Ops, Summary}; @@ -877,7 +613,7 @@ dialled(Name, Config, Secrets, {check, Expected, Fingerprint, Save}, Watcher, Ow {ok, Server, Expected} -> {ok, Server, Expected}; {ok, Server, Catalogue} -> - try Save(Name, Fingerprint, albedo_mcp_catalogue:encode_catalogue(Catalogue)) of + try Save(Name, Fingerprint, ?CATALOGUE:encode(Catalogue)) of _ -> Watcher ! {changed, Name}, {ok, Server, Catalogue} @@ -1081,29 +817,6 @@ close_client(#{client := Client, pid := Pid}) -> erlang:demonitor(Monitor, [flush]), ok. -valid_name(Name) -> - byte_size(Name) > 0 andalso byte_size(Name) =< 64 andalso - re:run(Name, <<"^[A-Za-z0-9][A-Za-z0-9_-]*$">>, [{capture, none}]) =:= match. - -positive_ms(Value) when is_integer(Value), Value > 0, Value =< 3600000 -> Value; -positive_ms(_) -> erlang:error(invalid_timeout). - -string_list(Value) when is_list(Value) -> - true = lists:all(fun is_binary/1, Value), - Value; -string_list(_) -> - erlang:error(invalid_args). -optional_binary(null) -> <<>>; -optional_binary(Value) when is_binary(Value) -> Value; -optional_binary(_) -> erlang:error(invalid_value). - -unavailable(Name) -> <<"MCP server '", Name/binary, "' is unavailable">>. - -%% A request the server refused before running it, for want of a sign-in. -needs_sign_in(Name, Reason) -> - <<"MCP server '", Name/binary, "' needs the user to sign in: ", Reason/binary, - ". The request did not run; ask the user to sign in from the MCP settings.">>. - %% The servers that were configured and enabled but could not be reached. offline(#{offline := Offline}) -> Offline. @@ -1132,7 +845,7 @@ check_candidate(Name, Config, Secrets) -> {needs_sign_in, _, _} -> {ok, nil}; _ -> - {error, unavailable(Name)} + {error, ?DISPATCH:unavailable(Name)} end end. @@ -1200,101 +913,3 @@ maybe_probe(Offline, Policy) -> end. now_ms() -> erlang:monotonic_time(millisecond). - -%% Validate persisted transport references and secret patches without resolving -%% environment variables or starting a client. -validate_settings(Name, Server, Secret) -> - try - true = valid_name(Name), - case Server of - none -> - ok; - {some, Config} when is_map(Config) -> - true = is_boolean(maps:get(<<"enabled">>, Config, true)), - lists:foreach( - fun(Field) -> _ = positive_ms(maps:get(Field, Config, ?DEFAULT_CALL_MS)) end, - [<<"startupTimeoutMs">>, <<"callTimeoutMs">>] - ), - lists:foreach( - fun(Field) -> - case maps:get(Field, Config, []) of - null when Field =:= <<"enabledTools">> -> ok; - Values -> _ = string_list(Values) - end - end, - [<<"args">>, <<"enabledTools">>, <<"disabledTools">>] - ), - case maps:get(<<"type">>, Config) of - <<"http">> -> - true = url_allowed(maps:get(<<"url">>, Config)); - <<"stdio">> -> - Command = maps:get(<<"command">>, Config), - true = is_binary(Command) andalso byte_size(Command) > 0 - end, - lists:foreach( - fun(Field) -> - maps:foreach( - fun(Target, Ref) -> - true = - case Field of - <<"headers">> -> valid_header(Target); - _ -> valid_env_name(Target) - end, - case Ref of - #{<<"env">> := EnvName} when map_size(Ref) =:= 1 -> - true = valid_env_name(EnvName); - Text when is_binary(Text) -> - case Field of - <<"headers">> -> false = contains_newline(Text); - _ -> ok - end; - _ -> - erlang:error(invalid_source) - end - end, - maps:get(Field, Config, #{}) - ) - end, - [<<"headers">>, <<"env">>] - ), - case maps:get(<<"bearerTokenEnvVar">>, Config, null) of - null -> ok; - RefName -> true = valid_env_name(RefName) - end - end, - true = is_map(Secret), - maps:foreach( - fun - (<<"bearerToken">>, null) -> - ok; - (<<"oauth">>, Record) -> - true = is_map(Record); - (<<"oauthClient">>, #{<<"clientId">> := Id}) -> - true = is_binary(Id); - (<<"bearerToken">>, Token) when is_binary(Token) -> false = contains_newline(Token); - (Field, null) when Field =:= <<"headers">>; Field =:= <<"env">> -> ok; - (Field, Changes) when Field =:= <<"headers">>; Field =:= <<"env">> -> - maps:foreach( - fun(K, V) -> - true = - case Field of - <<"headers">> -> valid_header(K); - _ -> valid_env_name(K) - end, - true = V =:= null orelse is_binary(V), - case {Field, V} of - {<<"headers">>, Text} when is_binary(Text) -> - false = contains_newline(Text); - _ -> - ok - end - end, - Changes - ) - end, - Secret - ), - {ok, nil} - catch - _:_ -> {error, <<"invalid MCP name, transport references, or credentials">>} - end. diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp_catalogue.erl b/src/albedo/harness/extensions/mcp/albedo_mcp_catalogue.erl deleted file mode 100644 index d7a3c1fc0..000000000 --- a/src/albedo/harness/extensions/mcp/albedo_mcp_catalogue.erl +++ /dev/null @@ -1,138 +0,0 @@ --module(albedo_mcp_catalogue). -%% External-term v2 compatibility and native binary/JSON boundaries only. --export([ - discover/1, - encode_catalogue/1, - saved/1, - bounded/2, - encoded_size/1, - encode_json/1, - flatten_whitespace/1, - invalid_annotation/2 -]). - --define(CATALOGUE, 'albedo@harness@extensions@mcp@catalogue'). - -%% Keep the native discovery entrypoint for lifecycle instrumentation. The -%% caller's existing catch boundary also handles malformed foreign values. -discover(#{name := Name, client := Client, call_timeout := Timeout, config := Config}) -> - try ?CATALOGUE:discover(Name, Client, Timeout, Config) of - {ok, {Operations, Summary}} -> {ok, Operations, Summary}; - {error, nil} -> {error, discovery_failed} - catch - _:_ -> {error, discovery_failed} - end. - -%% Existing saved catalogues use atom-keyed maps, not Gleam records. Keep the -%% exact v2 shape so both old and new daemons can read the same cache. -encode_catalogue({Operations, Summary}) -> - term_to_binary( - {2, [saved_operation(Operation) || Operation <- Operations], saved_summary(Summary)} - ). - -saved({some, Encoded}) when is_binary(Encoded) -> - try binary_to_term(Encoded, [safe]) of - {2, Operations, Summary} when is_list(Operations), is_map(Summary) -> - {ok, {[operation(Operation) || Operation <- Operations], summary(Summary)}}; - _ -> - none - catch - _:_ -> none - end; -saved(_) -> - none. - -saved_operation({operation, Advertised, Server, Kind, Raw, Timeout, Description, Schema, Headers}) -> - Operation = #{ - advertised => Advertised, - server => Server, - kind => Kind, - raw => Raw, - timeout => Timeout, - description => Description, - schema => Schema - }, - case Headers of - [] -> Operation; - _ -> Operation#{headers => Headers} - end. - -operation( - #{ - advertised := Advertised, - server := Server, - kind := Kind, - raw := Raw, - timeout := Timeout, - description := Description, - schema := Schema - } = Operation -) when - is_binary(Advertised), - is_binary(Server), - is_binary(Raw), - is_integer(Timeout), - is_binary(Description), - is_map(Schema), - (Kind =:= tool orelse Kind =:= resource orelse Kind =:= prompt) --> - Headers = maps:get(headers, Operation, []), - true = is_list(Headers), - true = lists:all( - fun - ({Path, Name}) -> - is_list(Path) andalso lists:all(fun is_binary/1, Path) andalso is_binary(Name); - (_) -> - false - end, - Headers - ), - {operation, Advertised, Server, Kind, Raw, Timeout, Description, Schema, Headers}. - -saved_summary({summary, Description, Resources, Templates, Prompts}) -> - #{ - description => Description, - resources => saved_items(Resources, <<"uri">>), - resource_templates => saved_items(Templates, <<"uriTemplate">>), - prompts => saved_items(Prompts, <<"name">>) - }. - -saved_items(Items, Key) -> - [ - #{Key => Identifier, <<"description">> => Description} - || {summary_item, Identifier, Description} <- Items - ]. - -summary(Summary) -> - Description = maps:get(description, Summary, <<>>), - true = is_binary(Description), - {summary, Description, items(maps:get(resources, Summary, []), <<"uri">>), - items(maps:get(resource_templates, Summary, []), <<"uriTemplate">>), - items(maps:get(prompts, Summary, []), <<"name">>)}. - -items(Items, Key) -> - lists:map( - fun(Item) -> - Identifier = maps:get(Key, Item, <<>>), - Description = maps:get(<<"description">>, Item, <<>>), - true = is_binary(Identifier) andalso is_binary(Description), - {summary_item, Identifier, Description} - end, - Items - ). - -bounded(Value, Limit) -> binary:part(Value, 0, min(byte_size(Value), Limit)). -encoded_size(Value) -> iolist_size(json:encode(Value)). -encode_json(Value) -> iolist_to_binary(json:encode(Value)). -flatten_whitespace(Value) -> - try - re:replace(Value, <<"\\s+">>, <<" ">>, [global, unicode, {return, binary}]) - catch - _:_ -> <<>> - end. -invalid_annotation(Server, Tool) -> - logger:warning( - "MCP server ~ts: tool ~ts has an invalid x-mcp-header and is left out", - [Server, Tool] - ), - nil. diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp_credentials.erl b/src/albedo/harness/extensions/mcp/albedo_mcp_credentials.erl deleted file mode 100644 index d839f9aa5..000000000 --- a/src/albedo/harness/extensions/mcp/albedo_mcp_credentials.erl +++ /dev/null @@ -1,27 +0,0 @@ --module(albedo_mcp_credentials). --include_lib("kernel/include/file.hrl"). --export([server/1, server_at/2]). - --define(MAX_BYTES, 1048576). - -%% Secrets never enter extension settings, prompt context or API responses. -%% They live in creds.json's "mcp" section. A missing file means no saved -%% credentials; a permissive file is an error. -server(Name) -> server_at(albedo_extension_settings:home(), Name). - -server_at(Home, Name) -> - Path = albedo_credentials:creds_path(Home), - case file:read_link_info(Path) of - {error, enoent} -> - {ok, #{}}; - {ok, #file_info{type = regular, size = Size, mode = Mode}} when - Size =< ?MAX_BYTES, Mode band 8#077 =:= 0 - -> - case albedo_credentials:mcp(Home) of - {ok, Servers} -> {ok, maps:get(Name, Servers, #{})}; - {error, enoent} -> {ok, #{}}; - {error, _} -> {error, <<"invalid creds.json">>} - end; - _ -> - {error, <<"creds.json must be a regular 0600 file under ~/.albedo">>} - end. diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl b/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl deleted file mode 100644 index d5fad9d29..000000000 --- a/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl +++ /dev/null @@ -1,841 +0,0 @@ --module(albedo_mcp_oauth). -%% OAuth for streamable HTTP MCP servers, as the MCP authorization spec asks -%% (2025-11-25 and 2026-07-28 basic/authorization): Protected Resource -%% Metadata discovery (RFC 9728), authorization server metadata (RFC 8414 and -%% OpenID Connect discovery, in the spec's order), a configured client or -%% Dynamic Client Registration (RFC 7591), the authorization code flow with -%% PKCE S256 and the resource parameter (RFC 8707), refresh, and step-up on -%% insufficient_scope. The sign-in service (oauth_flows) runs the browser half: its loopback -%% listener, state check and paste race. -%% -%% Each server's sign-in lives in creds.json under mcp..oauth, never -%% in extension settings. Its `state` is needs_sign_in, signed_in or -%% signed_out; `resource` is the server URL it belongs to, so a record left -%% by a server of the same name at another URL is never sent anywhere. - --export([ - access/4, - challenged/5, - discover/2, - authorize/2, - exchange/4, - account/2, - signed_in/3, - signed_out/1 -]). - --define(SKEW_MS, 60000). --define(REFRESH_WAIT_MS, 30000). --define(FETCH_MS, 15000). --define(MAX_BODY, 1048576). - -%% ---- tokens for requests ------------------------------------------------ - -%% The bearer token for the next request to `Url`: {ok, none} when the server -%% has no sign-in, {ok, {some, Token}}, or {error, Reason} when it needs one. -%% `Rejected` is the token the server just refused with 401, which is -%% refreshed once unless another request already replaced it. Refreshes of -%% one server are single-flight; a refresh the authorization server refuses -%% marks the server as needing sign-in instead of trying again. -access(Home, Name, Url, Rejected) -> - case record(Home, Name, Url) of - none -> - {ok, none}; - Record -> - case usable(Record, Rejected) of - {ok, Token} -> {ok, {some, Token}}; - stale -> refreshed(Home, Name, Url, Rejected); - {error, Reason} -> {error, Reason} - end - end. - -usable(#{<<"state">> := <<"signed_in">>, <<"access">> := Token} = Record, Rejected) when - is_binary(Token) --> - Fresh = - case maps:get(<<"expires">>, Record, null) of - Expires when is_integer(Expires) -> Expires - now_ms() > ?SKEW_MS; - _ -> true - end, - case {Fresh, Rejected} of - {true, none} -> {ok, Token}; - {true, {some, Other}} when Other =/= Token -> {ok, Token}; - _ -> stale - end; -usable(Record, _) -> - {error, reason(Record)}. - -refreshed(Home, Name, Url, Rejected) -> - Run = fun() -> - case record(Home, Name, Url) of - none -> - {ok, none}; - Record -> - case usable(Record, Rejected) of - {ok, Token} -> {ok, {some, Token}}; - {error, Reason} -> {error, Reason}; - stale -> refresh(Home, Name, Url, Record, Rejected) - end - end - end, - case albedo_lock:trans({?MODULE, Home, Name}, Run, ?REFRESH_WAIT_MS) of - {ok, Result} -> Result; - busy -> {error, <<"the sign-in is still refreshing">>} - end. - -refresh(Home, Name, Url, #{<<"refresh">> := Refresh} = Record, Rejected) when is_binary(Refresh) -> - Form = [ - {<<"grant_type">>, <<"refresh_token">>}, - {<<"refresh_token">>, Refresh}, - {<<"resource">>, maps:get(<<"resourceParameter">>, Record, Url)} - ], - case token_request(Record, Form) of - {ok, Tokens} -> - Next = with_tokens(Record, Tokens, maps:get(<<"scope">>, Record, null)), - update(Home, Name, Url, fun(_) -> Next end), - {ok, {some, maps:get(<<"access">>, Next)}}; - {refused, _} -> - Reason = <<"the saved sign-in expired; sign in again">>, - update(Home, Name, Url, fun(Current) -> needs_sign_in(Current, Reason) end), - {error, Reason}; - {error, Reason} -> - %% The authorization server could not be asked: a token that has - %% not been refused yet is still worth sending. - case {Rejected, maps:get(<<"access">>, Record, null)} of - {none, Token} when is_binary(Token) -> {ok, {some, Token}}; - _ -> {error, <<"could not refresh the sign-in: ", Reason/binary>>} - end - end; -refresh(Home, Name, Url, _, _) -> - Reason = <<"the sign-in expired; sign in again">>, - update(Home, Name, Url, fun(Current) -> needs_sign_in(Current, Reason) end), - {error, Reason}. - -%% Records what a 401 or 403 from the server says and returns the reason the -%% request cannot go on. A 401 to a server without a sign-in, or one whose -%% token was refused even after a refresh, needs sign-in; a 403 -%% insufficient_scope keeps the token and asks for the wider scope, the -%% union of what was asked before and what the challenge names (2026-07-28 -%% basic/authorization, "Step-Up Authorization Flow"). -challenged(Home, Name, Url, Status, Header) -> - Challenge = parse_challenge(Header), - Metadata = maps:get(<<"resource_metadata">>, Challenge, null), - Scope = maps:get(<<"scope">>, Challenge, null), - case {Status, maps:get(<<"error">>, Challenge, null)} of - {403, <<"insufficient_scope">>} -> - Wider = union(requested(record(Home, Name, Url)), Scope), - Reason = - <<"the server needs wider access (", Wider/binary, "); sign in again to grant it">>, - update(Home, Name, Url, fun(Current) -> - with_challenge( - Current#{<<"stepUp">> => Wider, <<"reason">> => Reason}, Metadata, null - ) - end), - Reason; - _ -> - Reason = - case record(Home, Name, Url) of - #{<<"state">> := <<"signed_in">>} -> - <<"the server refused the saved sign-in; sign in again">>; - #{<<"state">> := <<"signed_out">>} -> - <<"signed out">>; - _ -> - <<"the server asks you to sign in">> - end, - update(Home, Name, Url, fun(Current) -> - with_challenge(needs_sign_in(Current, Reason), Metadata, Scope) - end), - Reason - end. - -with_challenge(Record, Metadata, Scope) -> - Keep = fun - (_, null, R) -> R; - (Key, Value, R) when is_binary(Value) -> R#{Key => Value}; - (_, _, R) -> R - end, - Keep(<<"challengeScope">>, Scope, Keep(<<"resourceMetadata">>, Metadata, Record)). - -needs_sign_in(Record, Reason) -> - (maps:without([<<"access">>, <<"refresh">>, <<"expires">>], Record))#{ - <<"state">> => <<"needs_sign_in">>, <<"reason">> => Reason - }. - -%% A record whose tokens are dropped by the user; what the server asked for -%% and the client it registered stay for the next sign-in. -signed_out(Record) when is_map(Record) -> - (maps:without([<<"access">>, <<"refresh">>, <<"expires">>, <<"reason">>, <<"label">>], Record))#{ - <<"state">> => <<"signed_out">> - }; -signed_out(_) -> - #{<<"state">> => <<"signed_out">>}. - -reason(#{<<"state">> := <<"signed_out">>}) -> <<"signed out">>; -reason(#{<<"reason">> := Reason}) when is_binary(Reason) -> Reason; -reason(_) -> <<"the server asks you to sign in">>. - -requested(#{<<"stepUp">> := Scope}) when is_binary(Scope) -> Scope; -requested(#{<<"scope">> := Scope}) when is_binary(Scope) -> Scope; -requested(#{<<"challengeScope">> := Scope}) when is_binary(Scope) -> Scope; -requested(_) -> null. - -union(null, null) -> - <<>>; -union(A, null) -> - A; -union(null, B) -> - B; -union(A, B) -> - Words = - string:lexemes(A, " ") ++ - [W || W <- string:lexemes(B, " "), not lists:member(W, string:lexemes(A, " "))], - iolist_to_binary(lists:join(<<" ">>, Words)). - -%% The `Bearer` parameters of a WWW-Authenticate value (RFC 6750 section 3, -%% RFC 9728 section 5.1), lower-cased names to unquoted values. -parse_challenge(Header) when is_binary(Header) -> - Bearer = - case re:run(Header, <<"(?i)\\bbearer\\b(.*)">>, [{capture, [1], binary}]) of - {match, [Rest]} -> Rest; - nomatch -> <<>> - end, - case - re:run( - Bearer, - <<"([A-Za-z_]+)\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^,\\s]*))">>, - [global, {capture, all_but_first, binary}] - ) - of - {match, Pairs} -> - maps:from_list([ - {string:lowercase(Key), unquote(Quoted, Token)} - || [Key, Quoted, Token | _] <- [P ++ [<<>>] || P <- Pairs] - ]); - nomatch -> - #{} - end; -parse_challenge(_) -> - #{}. - -unquote(<<>>, Token) -> Token; -unquote(Quoted, _) -> re:replace(Quoted, <<"\\\\(.)">>, <<"\\1">>, [global, {return, binary}]). - -%% ---- sign-in ------------------------------------------------------------ - -%% Everything a sign-in needs before the browser opens: the server's -%% protected resource metadata, its authorization server's metadata, the -%% scope to ask for and how albedo is known to that server. -discover(Home, Name) -> - try - Url = server_url(Home, Name), - Record = - case record(Home, Name, Url) of - none -> #{}; - R -> R - end, - Resource = protected_resource(Url, maps:get(<<"resourceMetadata">>, Record, null)), - Parameter = resource_parameter(Url, maps:get(<<"resource">>, Resource, null)), - Issuer = - case maps:get(<<"authorization_servers">>, Resource, []) of - [First | _] when is_binary(First) -> First; - _ -> fail(<<"the server names no authorization server">>) - end, - allowed_endpoint(Url, Issuer), - Metadata = authorization_server(Url, Issuer), - Methods = maps:get(<<"code_challenge_methods_supported">>, Metadata, []), - case is_list(Methods) andalso lists:member(<<"S256">>, Methods) of - true -> ok; - false -> fail(<<"the authorization server does not support PKCE with S256">>) - end, - Client = client(Home, Name, Metadata), - {ok, #{ - home => Home, - name => Name, - url => Url, - resource => Parameter, - metadata_url => maps:get(<<"resourceMetadata">>, Record, null), - issuer => Issuer, - metadata => Metadata, - client => Client, - scope => scope(Record, Resource, Metadata) - }} - catch - throw:{mcp_oauth, Reason} -> {error, Reason}; - _:_ -> {error, <<"could not prepare the sign-in">>} - end. - -server_url(Home, Name) -> - Extensions = albedo_settings_store:read(Home, <<"extensions.json">>), - Servers = albedo_settings_store:object( - <<"servers">>, albedo_settings_store:object(<<"mcp">>, Extensions) - ), - case maps:get(Name, Servers, null) of - #{<<"type">> := <<"http">>, <<"url">> := Url} when is_binary(Url) -> Url; - null -> fail(<<"no MCP server is named ", Name/binary>>); - _ -> fail(<<"only HTTP MCP servers sign in">>) - end. - -%% The resource metadata the 401 named, else the well-known locations in the -%% spec's order: under the endpoint's path, then at the root. -protected_resource(Url, Named) -> - #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Url), - Origin = origin(Scheme, Host, maps:get(port, Parsed, undefined)), - Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), - WellKnown = - [<> || Path =/= <<>>] ++ - [<>], - Candidates = - case Named of - Value when is_binary(Value) -> - allowed_endpoint(Url, Value), - [Value]; - _ -> - WellKnown - end, - first_document( - Candidates, - fun(Document) -> is_list(maps:get(<<"authorization_servers">>, Document, null)) end, - <<"the server publishes no protected resource metadata">> - ). - -%% The resource parameter: the metadata's `resource` when the server URL is -%% it or lies under it (RFC 9728 section 3.3), else the server URL. -resource_parameter(Url, null) -> - canonical(Url); -resource_parameter(Url, Resource) when is_binary(Resource) -> - Canonical = canonical(Resource), - Server = canonical(Url), - case Server =:= Canonical orelse string:prefix(Server, <>) =/= nomatch of - true -> Canonical; - false -> fail(<<"the server's metadata names another resource">>) - end; -resource_parameter(_, _) -> - fail(<<"the server's metadata names no valid resource">>). - -canonical(Url) -> - #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Url), - Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), - Query = - case maps:get(query, Parsed, undefined) of - undefined -> <<>>; - Q -> <<"?", Q/binary>> - end, - << - (origin( - string:lowercase(Scheme), string:lowercase(Host), maps:get(port, Parsed, undefined) - ))/binary, - Path/binary, - Query/binary - >>. - -origin(Scheme, Host, Port) -> - Bracketed = - case binary:match(Host, <<":">>) of - nomatch -> Host; - _ -> <<"[", Host/binary, "]">> - end, - case Port of - undefined -> <>; - _ -> <> - end. - -%% RFC 8414 metadata, then OpenID Connect discovery, as the spec orders them -%% for an issuer with and without a path; a document whose `issuer` is not -%% the one asked for is not used. -authorization_server(Url, Issuer) -> - #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Issuer), - Origin = origin(Scheme, Host, maps:get(port, Parsed, undefined)), - Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), - Candidates = - case Path of - <<>> -> - [ - <>, - <> - ]; - _ -> - [ - <>, - <>, - <> - ] - end, - Metadata = first_document( - Candidates, - fun(Document) -> maps:get(<<"issuer">>, Document, null) =:= Issuer end, - <<"the authorization server publishes no metadata for its issuer">> - ), - lists:foreach( - fun(Key) -> - case maps:get(Key, Metadata, null) of - Endpoint when is_binary(Endpoint) -> allowed_endpoint(Url, Endpoint); - null when Key =:= <<"registration_endpoint">> -> ok; - _ -> fail(<<"the authorization server metadata has no ", Key/binary>>) - end - end, - [<<"authorization_endpoint">>, <<"token_endpoint">>, <<"registration_endpoint">>] - ), - Metadata. - -first_document([], _, Reason) -> - fail(Reason); -first_document([Candidate | Rest], Valid, Reason) -> - case fetch_json(get, Candidate, [], none) of - {ok, 200, Document} when is_map(Document) -> - case Valid(Document) of - true -> Document; - false -> first_document(Rest, Valid, Reason) - end; - _ -> - first_document(Rest, Valid, Reason) - end. - -%% Authorization server endpoints must use https (2025-11-25 -%% basic/authorization, "Communication Security"); a server the user reaches -%% over plain http on a network they trust may name plain http ones too. -allowed_endpoint(Url, Endpoint) -> - Http = string:prefix(Url, <<"http://">>) =/= nomatch, - case albedo_mcp:url_allowed(Endpoint) of - true -> - case string:prefix(Endpoint, <<"https://">>) =/= nomatch orelse Http of - true -> ok; - false -> fail(<<"the authorization server must use https">>) - end; - false -> - fail(<<"the authorization server named an invalid URL">>) - end. - -%% The scope to ask for: a pending step-up, else the 401's scope, else the -%% resource's scopes_supported (2026-07-28 basic/authorization, "Scope -%% Selection Strategy"), with offline_access when the authorization server -%% lists it, so a refresh token may come back. -scope(Record, Resource, Metadata) -> - Base = - case requested(Record) of - null -> - case maps:get(<<"scopes_supported">>, Resource, null) of - Scopes when is_list(Scopes), Scopes =/= [] -> - iolist_to_binary(lists:join(<<" ">>, Scopes)); - _ -> - null - end; - Scope -> - Scope - end, - Offline = lists:member( - <<"offline_access">>, - case maps:get(<<"scopes_supported">>, Metadata, []) of - L when is_list(L) -> L; - _ -> [] - end - ), - case {Base, Offline} of - {null, true} -> <<"offline_access">>; - {null, false} -> null; - {_, true} -> union(Base, <<"offline_access">>); - {_, false} -> Base - end. - -%% How albedo is known to the authorization server, in the spec's order -%% (2026-07-28 basic/authorization/client-registration): a client the user -%% configured for this server, then Dynamic Client Registration. Client ID -%% Metadata Documents come between them in the spec, but they need an https -%% URL albedo can host the document at, and a local daemon has none. -client(Home, Name, Metadata) -> - case configured_client(Home, Name) of - {ok, Client} -> - Client; - none -> - case maps:get(<<"registration_endpoint">>, Metadata, null) of - Endpoint when is_binary(Endpoint) -> {register, Endpoint}; - _ -> - fail( - <<"the authorization server offers no client registration; configure a client id for this server">> - ) - end - end. - -configured_client(Home, Name) -> - case albedo_credentials:mcp(Home) of - {ok, #{Name := #{<<"oauthClient">> := #{<<"clientId">> := Id} = Client}}} when - is_binary(Id), Id =/= <<>> - -> - {ok, {configured, Id, maps:get(<<"clientSecret">>, Client, null)}}; - _ -> - none - end. - -%% The authorize URL for one grant, registering albedo first when the -%% authorization server has no client for this redirect yet. -authorize( - #{metadata := Metadata, resource := Resource, scope := Scope} = Plan, - {grant, Redirect, State, _, Challenge, _} -) -> - try - {Id, _, _} = registered(Plan, Redirect), - Query = - [ - {<<"response_type">>, <<"code">>}, - {<<"client_id">>, Id}, - {<<"redirect_uri">>, Redirect}, - {<<"code_challenge">>, Challenge}, - {<<"code_challenge_method">>, <<"S256">>}, - {<<"state">>, State}, - {<<"resource">>, Resource} - ] ++ - [{<<"scope">>, Scope} || is_binary(Scope)], - Endpoint = maps:get(<<"authorization_endpoint">>, Metadata), - Separator = - case binary:match(Endpoint, <<"?">>) of - nomatch -> <<"?">>; - _ -> <<"&">> - end, - {ok, <>} - catch - throw:{mcp_oauth, Reason} -> {error, Reason}; - _:_ -> {error, <<"could not start the sign-in">>} - end. - -%% {ClientId, Secret, AuthMethod}: the configured client, a registration this -%% authorization server issued for `Redirect`, or a new one (RFC 7591), kept -%% per issuer so another authorization server never sees it. -registered(#{client := {configured, Id, Secret}}, _) -> - {Id, Secret, - case Secret of - null -> <<"none">>; - _ -> <<"client_secret_basic">> - end}; -registered( - #{client := {register, Endpoint}, home := Home, name := Name, url := Url, issuer := Issuer} = - Plan, - Redirect -) -> - Saved = - case record(Home, Name, Url) of - #{<<"registration">> := #{<<"issuer">> := Issuer, <<"redirectUri">> := Redirect} = R} -> - R; - _ -> - none - end, - case Saved of - #{<<"clientId">> := Id} = R2 -> - {Id, maps:get(<<"clientSecret">>, R2, null), - maps:get(<<"authMethod">>, R2, <<"none">>)}; - none -> - Request = #{ - <<"client_name">> => <<"albedo">>, - <<"redirect_uris">> => [Redirect], - <<"grant_types">> => [<<"authorization_code">>, <<"refresh_token">>], - <<"response_types">> => [<<"code">>], - <<"token_endpoint_auth_method">> => <<"none">>, - <<"application_type">> => <<"native">> - }, - Body = iolist_to_binary( - json:encode( - case maps:get(scope, Plan) of - Scope when is_binary(Scope) -> Request#{<<"scope">> => Scope}; - _ -> Request - end - ) - ), - case fetch_json(post, Endpoint, [], {<<"application/json">>, Body}) of - {ok, Status, #{<<"client_id">> := Id} = Answer} when - Status =:= 200; Status =:= 201 - -> - Secret = - case maps:get(<<"client_secret">>, Answer, null) of - S when is_binary(S) -> S; - _ -> null - end, - Method = - case maps:get(<<"token_endpoint_auth_method">>, Answer, null) of - M when is_binary(M) -> M; - _ when Secret =:= null -> <<"none">>; - _ -> <<"client_secret_basic">> - end, - Registration = #{ - <<"issuer">> => Issuer, - <<"redirectUri">> => Redirect, - <<"clientId">> => Id, - <<"clientSecret">> => Secret, - <<"authMethod">> => Method - }, - update(Home, Name, Url, fun(Current) -> - Current#{<<"registration">> => Registration} - end), - {Id, Secret, Method}; - {ok, Status, Answer} -> - fail(described(<<"client registration">>, Status, Answer)); - {error, Reason} -> - fail(Reason) - end - end. - -%% Trades the authorization code for tokens and returns the credential the -%% sign-in stores. An `iss` in the response must be the issuer albedo asked -%% (RFC 9207 section 2.4), and one the server promised must be there. -exchange( - #{metadata := Metadata, issuer := Issuer, resource := Resource, scope := Scope} = Plan, - {grant, Redirect, _, Verifier, _, _}, - Code, - Iss -) -> - try - Promised = - maps:get(<<"authorization_response_iss_parameter_supported">>, Metadata, false) =:= - true, - case {Iss, Promised} of - {{some, Issuer}, _} -> ok; - {{some, _}, _} -> fail(<<"the authorization response came from another issuer">>); - {none, true} -> fail(<<"the authorization response did not name its issuer">>); - {none, false} -> ok - end, - {Id, Secret, Method} = registered(Plan, Redirect), - Client = #{ - <<"tokenEndpoint">> => maps:get(<<"token_endpoint">>, Metadata), - <<"clientId">> => Id, - <<"clientSecret">> => Secret, - <<"authMethod">> => Method - }, - Form = [ - {<<"grant_type">>, <<"authorization_code">>}, - {<<"code">>, Code}, - {<<"redirect_uri">>, Redirect}, - {<<"code_verifier">>, Verifier}, - {<<"resource">>, Resource} - ], - case token_request(Client, Form) of - {ok, Tokens} -> - Base = Client#{ - <<"issuer">> => Issuer, - <<"resource">> => maps:get(url, Plan), - <<"resourceParameter">> => Resource, - <<"resourceMetadata">> => maps:get(metadata_url, Plan) - }, - {ok, with_tokens(Base, Tokens, Scope)}; - {refused, Reason} -> - fail(Reason); - {error, Reason} -> - fail(Reason) - end - catch - throw:{mcp_oauth, Failure} -> {error, Failure}; - _:_ -> {error, <<"could not finish the sign-in">>} - end. - -%% A credential with the token response folded in: the access token, a new -%% refresh token or the old one, when it expires, the granted scope, and the -%% account a token names, for "signed in as". -with_tokens(Record, Tokens, Requested) -> - Expires = - case maps:get(<<"expires_in">>, Tokens, null) of - Seconds when is_integer(Seconds), Seconds > 0 -> now_ms() + Seconds * 1000; - _ -> null - end, - Refresh = - case maps:get(<<"refresh_token">>, Tokens, null) of - R when is_binary(R) -> R; - _ -> maps:get(<<"refresh">>, Record, null) - end, - Granted = - case maps:get(<<"scope">>, Tokens, null) of - S when is_binary(S) -> S; - _ -> Requested - end, - Label = account_label( - Tokens, maps:get(<<"label">>, Record, null), maps:get(<<"issuer">>, Record, <<>>) - ), - maps:without([<<"reason">>, <<"stepUp">>], Record#{ - <<"state">> => <<"signed_in">>, - <<"access">> => maps:get(<<"access_token">>, Tokens), - <<"refresh">> => Refresh, - <<"expires">> => Expires, - <<"scope">> => Granted, - <<"label">> => Label - }). - -account_label(Tokens, Previous, Issuer) -> - Claims = [ - C - || Key <- [<<"id_token">>, <<"access_token">>], - Token <- [maps:get(Key, Tokens, null)], - C <- [jwt_claims(Token)], - is_map(C) - ], - Named = [ - V - || C <- Claims, - Key <- [<<"email">>, <<"preferred_username">>, <<"name">>, <<"sub">>], - V <- [maps:get(Key, C, null)], - is_binary(V), - V =/= <<>> - ], - case {Named, Previous} of - {[Name | _], _} -> - bounded(Name, 256); - {[], P} when is_binary(P) -> P; - _ -> - case uri_string:parse(Issuer) of - #{host := Host} -> Host; - _ -> Issuer - end - end. - -jwt_claims(Token) when is_binary(Token) -> - case binary:split(Token, <<".">>, [global]) of - [_, Payload, _] -> - try - json:decode(base64:decode(Payload, #{mode => urlsafe, padding => false})) - catch - _:_ -> none - end; - _ -> - none - end; -jwt_claims(_) -> - none. - -%% The account a stored credential names: one per server, so a new sign-in -%% replaces the last. -account(Name, Credential) -> - Label = - case maps:get(<<"label">>, Credential, null) of - L when is_binary(L) -> L; - _ -> Name - end, - {account, <<"mcp:", Name/binary>>, Label, <<"MCP server ", Name/binary>>, false}. - -%% Creds with this server's signed-in credential in place, keeping the -%% registration an earlier sign-in made; the sign-in service calls it under the lock. -signed_in(Creds, Name, Credential) -> - Servers = albedo_settings_store:object(<<"mcp">>, Creds), - Secrets = maps:get(Name, Servers, #{}), - Previous = - case maps:get(<<"oauth">>, Secrets, #{}) of - P when is_map(P) -> P; - _ -> #{} - end, - Kept = maps:with([<<"registration">>, <<"challengeScope">>], Previous), - Creds#{<<"mcp">> => Servers#{Name => Secrets#{<<"oauth">> => maps:merge(Kept, Credential)}}}. - -%% ---- token endpoint ----------------------------------------------------- - -%% {ok, Tokens}, {refused, Reason} when the authorization server answered -%% with an OAuth error, or {error, Reason} when it could not be asked. -token_request(#{<<"tokenEndpoint">> := Endpoint, <<"clientId">> := Id} = Client, Form0) -> - Secret = maps:get(<<"clientSecret">>, Client, null), - {Form, Headers} = - case {maps:get(<<"authMethod">>, Client, <<"none">>), Secret} of - {<<"client_secret_basic">>, S} when is_binary(S) -> - Basic = base64:encode(<<(form_encode(Id))/binary, ":", (form_encode(S))/binary>>), - {Form0, [{<<"authorization">>, <<"Basic ", Basic/binary>>}]}; - {<<"client_secret_post">>, S} when is_binary(S) -> - {Form0 ++ [{<<"client_id">>, Id}, {<<"client_secret">>, S}], []}; - _ -> - {Form0 ++ [{<<"client_id">>, Id}], []} - end, - Body = uri_string:compose_query(Form), - case fetch_json(post, Endpoint, Headers, {<<"application/x-www-form-urlencoded">>, Body}) of - {ok, 200, #{<<"access_token">> := Access} = Tokens} when is_binary(Access) -> - case string:lowercase(maps:get(<<"token_type">>, Tokens, <<"bearer">>)) of - <<"bearer">> -> {ok, Tokens}; - _ -> {refused, <<"the authorization server issued a token albedo cannot send">>} - end; - {ok, Status, Answer} when Status >= 400, Status < 500 -> - {refused, described(<<"the token request">>, Status, Answer)}; - {ok, Status, Answer} -> - {error, described(<<"the token request">>, Status, Answer)}; - {error, Reason} -> - {error, Reason} - end. - -%% A client id or secret as application/x-www-form-urlencoded, which HTTP -%% Basic carries for OAuth (RFC 6749 section 2.3.1). -form_encode(Value) -> iolist_to_binary(uri_string:compose_query([{Value, true}])). - -described(What, _, #{<<"error">> := Error} = Answer) when is_binary(Error) -> - Detail = - case maps:get(<<"error_description">>, Answer, null) of - D when is_binary(D) -> <<": ", (bounded(D, 512))/binary>>; - _ -> <<>> - end, - <>; -described(What, Status, _) -> - <>. - -fetch_json(Method, Url, Headers, Body) -> - case - albedo_http:request( - Method, - Url, - [{<<"accept">>, <<"application/json">>} | Headers], - Body, - ?FETCH_MS, - ?FETCH_MS - ) - of - {ok, {Status, _, Response}} when byte_size(Response) =< ?MAX_BODY -> - Decoded = - try - json:decode(Response) - catch - _:_ -> none - end, - {ok, Status, Decoded}; - {ok, _} -> - {error, <<"the answer was too large">>}; - _ -> - Host = - case uri_string:parse(Url) of - #{host := H} -> H; - _ -> Url - end, - {error, <<"could not reach ", Host/binary>>} - end. - -%% ---- creds.json --------------------------------------------------------- - -%% This server's sign-in record when it belongs to `Url`, else none. -record(Home, Name, Url) -> - case albedo_credentials:mcp(Home) of - {ok, #{Name := #{<<"oauth">> := #{<<"resource">> := Url} = Record}}} -> Record; - _ -> none - end. - -%% Replaces this server's record with `Change(Current)` under the settings -%% lock; a record for another URL is started afresh. -update(Home, Name, Url, Change) -> - albedo_settings_store:with_lock(Home, fun() -> - albedo_settings_store:guarded(fun() -> - Creds = albedo_settings_store:read(Home, <<"creds.json">>), - Servers = albedo_settings_store:object(<<"mcp">>, Creds), - Secrets = maps:get(Name, Servers, #{}), - Current = - case maps:get(<<"oauth">>, Secrets, null) of - #{<<"resource">> := Url} = R -> R; - _ -> #{<<"resource">> => Url, <<"state">> => <<"needs_sign_in">>} - end, - Next = Change(Current), - case Next =:= Current of - true -> - ok; - false -> - albedo_settings_store:commit_group( - Home, - #{ - <<"creds.json">> => Creds#{ - <<"mcp">> => Servers#{Name => Secrets#{<<"oauth">> => Next}} - } - } - ) - end, - {ok, nil} - end) - end). - -fail(Reason) -> throw({mcp_oauth, Reason}). - -bounded(Text, Max) -> - unicode:characters_to_binary(lists:sublist(unicode:characters_to_list(Text), Max)). - -now_ms() -> erlang:system_time(millisecond). diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp_stdio.erl b/src/albedo/harness/extensions/mcp/albedo_mcp_stdio.erl index 77dbe5a08..69fe604cd 100644 --- a/src/albedo/harness/extensions/mcp/albedo_mcp_stdio.erl +++ b/src/albedo/harness/extensions/mcp/albedo_mcp_stdio.erl @@ -1,8 +1,10 @@ -module(albedo_mcp_stdio). %% The port a stdio MCP server runs behind, owned by the client process that -%% opens it: newline-delimited frames in, lines out. +%% opens it: newline-delimited frames in, lines out. Also the OS lookups a +%% transport needs: daemon variables, executables, and the launcher script. -export([open/3, send/2, close/1, classify/2]). +-export([environment/2, variable/1, executable/1, launcher/0]). %% Lines longer than this arrive in pieces the client joins. -define(LINE_BYTES, 1048576). @@ -47,3 +49,53 @@ classify(Port, {Port, {data, {eol, Bytes}}}) -> {line, Bytes, true}; classify(Port, {Port, {data, {noeol, Bytes}}}) -> {line, Bytes, false}; classify(Port, {Port, {exit_status, Status}}) -> {exited, Status}; classify(_, _) -> other. + +%% The port's env list for a server given exactly `Given`, keeping only the +%% daemon variables in `Keep`. A port applies its env list in order, and a +%% later {Name, false} unsets a name an earlier entry set. A server given the +%% daemon's own variable name is the normal case, and that name is in the +%% removal list: removals go first, and never name a variable this server was +%% given. +environment(Given, Keep) -> + Set = [{binary_to_list(Name), binary_to_list(Value)} || {Name, Value} <- Given], + Names = [Name || {Name, _} <- Set] ++ [binary_to_list(Name) || Name <- Keep], + Removed = [ + {Name, false} + || Entry <- os:env(), + Name <- [env_name(Entry)], + not lists:member(Name, Names) + ], + Removed ++ Set. + +env_name({Name, _}) when is_list(Name) -> Name; +env_name(Entry) when is_list(Entry) -> hd(string:split(Entry, "=", leading)). + +%% The daemon's value of variable `Name`, when it is set. +variable(Name) -> + case os:getenv(binary_to_list(Name)) of + false -> {error, nil}; + Value -> {ok, unicode:characters_to_binary(Value)} + end. + +%% An absolute path to a regular file as given, else the command found on PATH. +executable(Command) -> + Value = binary_to_list(Command), + case filename:pathtype(Value) of + absolute -> + case filelib:is_regular(Value) of + true -> {ok, Command}; + false -> {error, nil} + end; + _ -> + case os:find_executable(Value) of + false -> {error, nil}; + Path -> {ok, unicode:characters_to_binary(Path)} + end + end. + +%% The Python script a stdio server is launched through. +launcher() -> + case albedo_priv:dir() of + {error, _} -> {error, nil}; + Dir -> {ok, unicode:characters_to_binary(filename:join([Dir, "python", "mcp_stdio.py"]))} + end. diff --git a/src/albedo/harness/extensions/mcp/catalogue.gleam b/src/albedo/harness/extensions/mcp/catalogue.gleam index c3df385b4..fef42b332 100644 --- a/src/albedo/harness/extensions/mcp/catalogue.gleam +++ b/src/albedo/harness/extensions/mcp/catalogue.gleam @@ -1,14 +1,20 @@ -//// MCP catalogue policy. Native code owns connections and the versioned -//// external-term cache; operations remain typed between those boundaries. +//// MCP catalogue policy and the versioned external-term cache. Native code +//// owns connections; operations remain typed inside the runtime. import albedo/harness/extensions/mcp/client import albedo/harness/extensions/mcp/param_headers import albedo/harness/sdk/digest +import albedo/harness/sdk/log +import albedo/harness/sdk/protect +import albedo/harness/sdk/term_codec +import albedo/openai_api/types import gleam/bit_array import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode +import gleam/erlang/atom +import gleam/json import gleam/list -import gleam/option.{None, Some} +import gleam/option.{type Option, None, Some} import gleam/result import gleam/string @@ -474,17 +480,266 @@ pub fn valid(operations: List(Operation)) -> Bool { && list.length(list.unique(names)) == list.length(names) } -@external(erlang, "albedo_mcp_catalogue", "bounded") -fn bounded(value: String, limit: Int) -> String +/// The longest prefix of `value` that is at most `limit` bytes and ends on a +/// character boundary. +fn bounded(value: String, limit: Int) -> String { + case string.byte_size(value) <= limit { + True -> value + False -> byte_prefix(bit_array.from_string(value), limit) + } +} -@external(erlang, "albedo_mcp_catalogue", "encoded_size") -fn encoded_size(value: Dynamic) -> Int +fn byte_prefix(bytes: BitArray, limit: Int) -> String { + case bit_array.slice(bytes, 0, limit) |> result.try(bit_array.to_string) { + Ok(prefix) -> prefix + Error(Nil) -> byte_prefix(bytes, limit - 1) + } +} -@external(erlang, "albedo_mcp_catalogue", "encode_json") -fn encode_json(value: Dynamic) -> String +fn encoded_size(value: Dynamic) -> Int { + encode_json(value) |> string.byte_size +} -@external(erlang, "albedo_mcp_catalogue", "flatten_whitespace") -fn flatten_whitespace(value: String) -> String +fn encode_json(value: Dynamic) -> String { + types.encode_value(value) |> json.to_string +} -@external(erlang, "albedo_mcp_catalogue", "invalid_annotation") -fn invalid_annotation(server: String, tool: String) -> Nil +/// Each run of ASCII whitespace as one space. +fn flatten_whitespace(value: String) -> String { + value + |> string.to_utf_codepoints + |> list.fold(#([], False), fn(state, codepoint) { + let #(output, spaced) = state + case string.utf_codepoint_to_int(codepoint) { + 9 | 10 | 11 | 12 | 13 | 32 if spaced -> state + 9 | 10 | 11 | 12 | 13 | 32 -> #([space(), ..output], True) + _ -> #([codepoint, ..output], False) + } + }) + |> fn(state) { list.reverse(state.0) } + |> string.from_utf_codepoints +} + +fn space() -> UtfCodepoint { + let assert [space] = string.to_utf_codepoints(" ") + space +} + +fn invalid_annotation(server: String, tool: String) -> Nil { + log.warning( + "MCP server " + <> server + <> ": tool " + <> tool + <> " has an invalid x-mcp-header and is left out", + ) +} + +/// Discovery for the native connection lifecycle, which instruments this +/// entrypoint. A crash on a malformed server value fails discovery. +pub fn discover_guarded( + name: String, + connection: client.Client, + timeout: Int, + config: Dynamic, +) -> Result(#(List(Operation), Summary), Nil) { + protect.attempt(fn() { discover(name, connection, timeout, config) }) + |> result.replace_error(Nil) + |> result.flatten +} + +// Saved catalogues use the version 2 external-term cache: atom-keyed maps, +// not Gleam records, so old and new daemons read the same rows. + +/// A catalogue as saved in `mcp_catalogues`. +pub fn encode(catalogue: #(List(Operation), Summary)) -> BitArray { + let #(operations, summary) = catalogue + term_codec.encode(#( + 2, + list.map(operations, saved_operation), + saved_summary(summary), + )) +} + +/// The catalogue a saved row holds, or None when it is not one this daemon +/// can read. +pub fn saved(value: Option(BitArray)) -> Option(#(List(Operation), Summary)) { + case value { + None -> None + Some(encoded) -> + case term_codec.decode_safe(encoded) { + Error(Nil) -> None + Ok(term) -> decode.run(term, saved_decoder()) |> option.from_result + } + } +} + +fn key(name: String) -> Dynamic { + atom.to_dynamic(atom.create(name)) +} + +fn saved_operation(operation: Operation) -> Dynamic { + let fields = [ + #(key("advertised"), dynamic.string(operation.advertised)), + #(key("server"), dynamic.string(operation.server)), + #(key("kind"), key(kind_name(operation.kind))), + #(key("raw"), dynamic.string(operation.raw)), + #(key("timeout"), dynamic.int(operation.timeout)), + #(key("description"), dynamic.string(operation.description)), + #(key("schema"), operation.schema), + ] + case operation.headers { + [] -> dynamic.properties(fields) + headers -> + dynamic.properties([ + #( + key("headers"), + dynamic.list( + list.map(headers, fn(header) { + dynamic.array([ + dynamic.list(list.map(header.0, dynamic.string)), + dynamic.string(header.1), + ]) + }), + ), + ), + ..fields + ]) + } +} + +fn saved_summary(summary: Summary) -> Dynamic { + dynamic.properties([ + #(key("description"), dynamic.string(summary.description)), + #(key("resources"), saved_items(summary.resources, "uri")), + #( + key("resource_templates"), + saved_items(summary.resource_templates, "uriTemplate"), + ), + #(key("prompts"), saved_items(summary.prompts, "name")), + ]) +} + +fn saved_items(items: List(SummaryItem), name: String) -> Dynamic { + dynamic.list( + list.map(items, fn(item) { + object([ + #(name, dynamic.string(item.identifier)), + #("description", dynamic.string(item.description)), + ]) + }), + ) +} + +fn saved_decoder() -> decode.Decoder(#(List(Operation), Summary)) { + use <- tuple(3) + use version <- decode.field(0, decode.int) + use operations <- decode.field(1, decode.list(saved_operation_decoder())) + use summary <- decode.field(2, saved_summary_decoder()) + case version { + 2 -> decode.success(#(operations, summary)) + _ -> decode.failure(#(operations, summary), "version 2 catalogue") + } +} + +/// `next` for an Erlang tuple of exactly `size` elements. +fn tuple(size: Int, next: fn() -> decode.Decoder(a)) -> decode.Decoder(a) { + use value <- decode.then(decode.dynamic) + let sized = + dynamic.classify(value) == "Array" + && result.is_ok(decode.run(value, decode.at([size - 1], decode.dynamic))) + && result.is_error(decode.run(value, decode.at([size], decode.dynamic))) + case sized { + True -> next() + False -> decode.then(decode.failure(Nil, "tuple"), fn(_) { next() }) + } +} + +fn saved_operation_decoder() -> decode.Decoder(Operation) { + use advertised <- decode.field(key("advertised"), decode.string) + use server <- decode.field(key("server"), decode.string) + use kind <- decode.field(key("kind"), kind_decoder()) + use raw <- decode.field(key("raw"), decode.string) + use timeout <- decode.field(key("timeout"), decode.int) + use description <- decode.field(key("description"), decode.string) + use schema <- decode.field(key("schema"), decode.dynamic) + use headers <- decode.optional_field( + key("headers"), + [], + decode.list({ + use <- tuple(2) + use path <- decode.field(0, decode.list(decode.string)) + use name <- decode.field(1, decode.string) + decode.success(#(path, name)) + }), + ) + case is_object(schema) { + True -> + decode.success(Operation( + advertised, + server, + kind, + raw, + timeout, + description, + schema, + headers, + )) + False -> + decode.failure( + Operation( + advertised, + server, + kind, + raw, + timeout, + description, + schema, + headers, + ), + "object schema", + ) + } +} + +fn kind_decoder() -> decode.Decoder(Kind) { + use kind <- decode.then(atom.decoder()) + case atom.to_string(kind) { + "tool" -> decode.success(Tool) + "resource" -> decode.success(Resource) + "prompt" -> decode.success(Prompt) + _ -> decode.failure(Tool, "operation kind") + } +} + +fn saved_summary_decoder() -> decode.Decoder(Summary) { + use _ <- decode.then(decode.dict(decode.dynamic, decode.dynamic)) + use description <- decode.optional_field( + key("description"), + "", + decode.string, + ) + use resources <- decode.optional_field( + key("resources"), + [], + decode.list(saved_item_decoder("uri")), + ) + use templates <- decode.optional_field( + key("resource_templates"), + [], + decode.list(saved_item_decoder("uriTemplate")), + ) + use prompts <- decode.optional_field( + key("prompts"), + [], + decode.list(saved_item_decoder("name")), + ) + decode.success(Summary(description, resources, templates, prompts)) +} + +fn saved_item_decoder(name: String) -> decode.Decoder(SummaryItem) { + use _ <- decode.then(decode.dict(decode.dynamic, decode.dynamic)) + use identifier <- decode.optional_field(name, "", decode.string) + use description <- decode.optional_field("description", "", decode.string) + decode.success(SummaryItem(identifier, description)) +} diff --git a/src/albedo/harness/extensions/mcp/dispatch.gleam b/src/albedo/harness/extensions/mcp/dispatch.gleam new file mode 100644 index 000000000..59f30818b --- /dev/null +++ b/src/albedo/harness/extensions/mcp/dispatch.gleam @@ -0,0 +1,125 @@ +//// One call to an advertised operation: the request its kind sends, the +//// size limit on its result, and what a caller is told when it cannot run. +//// The native lifecycle owns the worker that runs it and its deadline. + +import albedo/harness/extensions/mcp/catalogue +import albedo/harness/extensions/mcp/client +import albedo/harness/extensions/mcp/param_headers +import albedo/openai_api/types +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/json +import gleam/list +import gleam/string + +const max_result_bytes = 4_194_304 + +/// Sends `operation` with `arguments` to its server's client: a tool call, +/// a resource read by `uri`, or a prompt by `name` with its `arguments`. +pub fn dispatch( + operation: catalogue.Operation, + connection: client.Client, + arguments: Dynamic, +) -> Result(Dynamic, client.Failure) { + case operation.kind { + catalogue.Tool -> + client.request_with( + connection, + "tools/call", + encode( + object([ + #("name", dynamic.string(operation.raw)), + #("arguments", arguments), + ]), + ), + param_headers.values(operation.headers, arguments), + operation.timeout, + ) + catalogue.Resource -> + case decode.run(arguments, decode.at(["uri"], decode.string)) { + Ok(uri) -> + request( + connection, + "resources/read", + [#("uri", dynamic.string(uri))], + operation.timeout, + ) + Error(_) -> Error(invalid_arguments) + } + catalogue.Prompt -> + case decode.run(arguments, prompt_decoder()) { + Ok(#(name, prompt_arguments)) -> + request( + connection, + "prompts/get", + [ + #("name", dynamic.string(name)), + #("arguments", prompt_arguments), + ], + operation.timeout, + ) + Error(_) -> Error(invalid_arguments) + } + } +} + +const invalid_arguments = client.Invalid("invalid arguments") + +fn prompt_decoder() -> decode.Decoder(#(String, Dynamic)) { + use name <- decode.field("name", decode.string) + use prompt_arguments <- decode.optional_field( + "arguments", + object([]), + decode.dynamic, + ) + case + decode.run(prompt_arguments, decode.dict(decode.dynamic, decode.dynamic)) + { + Ok(_) -> decode.success(#(name, prompt_arguments)) + Error(_) -> decode.failure(#(name, prompt_arguments), "prompt arguments") + } +} + +fn request( + connection: client.Client, + method: String, + params: List(#(String, Dynamic)), + timeout: Int, +) -> Result(Dynamic, client.Failure) { + client.request(connection, method, encode(object(params)), timeout) +} + +/// A server's result as JSON, when it is within the safe output limit. +pub fn encode_result(value: Dynamic) -> Result(String, String) { + let encoded = encode(value) + case string.byte_size(encoded) <= max_result_bytes { + True -> Ok(encoded) + False -> Error("MCP result exceeded the safe output limit") + } +} + +pub fn unavailable(name: String) -> String { + "MCP server '" <> name <> "' is unavailable" +} + +/// A request the server refused before running it, for want of a sign-in. +pub fn needs_sign_in(name: String, reason: String) -> String { + "MCP server '" + <> name + <> "' needs the user to sign in: " + <> reason + <> ". The request did not run; ask the user to sign in from the MCP settings." +} + +fn object(fields: List(#(String, Dynamic))) -> Dynamic { + fields + |> dict.from_list + |> dict.to_list + |> list.map(fn(field) { #(dynamic.string(field.0), field.1) }) + |> dynamic.properties +} + +fn encode(value: Dynamic) -> String { + types.encode_value(value) |> json.to_string +} diff --git a/src/albedo/harness/extensions/mcp/extension.gleam b/src/albedo/harness/extensions/mcp/extension.gleam index e8062a0f6..2c49806d4 100644 --- a/src/albedo/harness/extensions/mcp/extension.gleam +++ b/src/albedo/harness/extensions/mcp/extension.gleam @@ -1,5 +1,6 @@ //// Session-owned MCP clients and dynamically discovered capabilities. +import albedo/harness/extensions/mcp/servers import albedo/harness/extensions/mcp/sign_in import albedo/harness/extensions/mcp/transfer import albedo/harness/sdk/editor_mcp @@ -175,7 +176,7 @@ pub fn configured_extension() -> extension.Extension { extension.McpServersPlugin(extension.McpServers( configured_names, fn(name, definition, secret) { - native_validate_settings(name, Some(definition), secret) + servers.validate_settings(name, Some(definition), secret) }, native_check_candidate, sign_in.signed_out, @@ -224,13 +225,6 @@ fn configured_names() -> Result(List(String), String) { |> result.map(fn(config) { dict.keys(config.servers) }) } -@external(erlang, "albedo_mcp", "validate_settings") -fn native_validate_settings( - name: String, - definition: Option(Dynamic), - secret: Dynamic, -) -> Result(Nil, String) - @external(erlang, "albedo_mcp", "check_candidate") fn native_check_candidate( name: String, diff --git a/src/albedo/harness/extensions/mcp/oauth.gleam b/src/albedo/harness/extensions/mcp/oauth.gleam new file mode 100644 index 000000000..369ddd398 --- /dev/null +++ b/src/albedo/harness/extensions/mcp/oauth.gleam @@ -0,0 +1,1389 @@ +//// OAuth for streamable HTTP MCP servers, as the MCP authorization spec asks +//// (2025-11-25 and 2026-07-28 basic/authorization): Protected Resource +//// Metadata discovery (RFC 9728), authorization server metadata (RFC 8414 and +//// OpenID Connect discovery, in the spec's order), a configured client or +//// Dynamic Client Registration (RFC 7591), the authorization code flow with +//// PKCE S256 and the resource parameter (RFC 8707), refresh, and step-up on +//// insufficient_scope. The sign-in service (oauth_flows) runs the browser +//// half: its loopback listener, state check and paste race. +//// +//// Each server's sign-in lives in creds.json under mcp..oauth, never +//// in extension settings. Its `state` is needs_sign_in, signed_in or +//// signed_out. Its `resource` is the server URL it belongs to, so a record +//// left by a server of the same name at another URL is never sent anywhere. + +import albedo/clock +import albedo/harness/extensions/mcp/client +import albedo/harness/sdk/file +import albedo/harness/sdk/http +import albedo/harness/sdk/oauth +import albedo/harness/sdk/protect +import albedo/harness/sdk/settings_documents +import albedo/harness/sdk/term +import albedo/harness/sdk/text as patterns +import albedo/openai_api/types +import albedo/text_scalars +import gleam/bit_array +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string +import gleam/uri + +const skew_ms = 60_000 + +const refresh_wait_ms = 30_000 + +const fetch_ms = 15_000 + +const max_body = 1_048_576 + +/// A sign-in record, a token response, or a metadata document. +type Object = + Dict(String, Dynamic) + +/// Why a step stopped: a reason the user sees, or a value albedo could not +/// use, which each entrypoint reports in its own words. +type Failure { + Failed(String) + Broken +} + +/// What discovery found for one server, everything a sign-in needs before +/// the browser opens. +pub opaque type Plan { + Plan( + home: String, + name: String, + url: String, + resource: String, + metadata_url: Dynamic, + issuer: String, + metadata: Object, + client: ClientSource, + scope: Option(String), + ) +} + +/// How albedo is known to the authorization server. +type ClientSource { + Configured(id: String, secret: Dynamic) + Register(endpoint: String) +} + +/// A client albedo authenticates as: its id, its secret or null, and how the +/// token endpoint expects the secret. +type Registered { + Registered(id: String, secret: Dynamic, method: Dynamic) +} + +type TokenAnswer { + Tokens(Object) + /// The authorization server answered with an OAuth error. + Refused(String) + /// The authorization server could not be asked. + Unasked(String) +} + +// ---- tokens for requests ------------------------------------------------ + +/// The client.Auth for one server's OAuth sign-in in `home`. +pub fn auth(home: String, name: String, url: String) -> client.Auth { + client.Auth( + fn(refused) { access(home, name, url, refused) }, + fn(status, challenge) { challenged(home, name, url, status, challenge) }, + ) +} + +/// The bearer token for the next request to `url`: None when the server has +/// no sign-in, or Error with the reason when it needs one. `rejected` is the +/// token the server just refused with 401, which is refreshed once unless +/// another request already replaced it. Refreshes of one server are +/// single-flight. A refresh the authorization server refuses marks the server +/// as needing sign-in instead of trying again. +pub fn access( + home: String, + name: String, + url: String, + rejected: Option(String), +) -> Result(Option(String), String) { + case record(home, name, url) { + None -> Ok(None) + Some(saved) -> + case usable(saved, rejected) { + Ok(Some(token)) -> Ok(Some(token)) + Ok(None) -> refreshed(home, name, url, rejected) + Error(reason) -> Error(reason) + } + } +} + +/// Ok(Some(token)) for a token worth sending, Ok(None) for one to refresh. +fn usable( + saved: Object, + rejected: Option(String), +) -> Result(Option(String), String) { + case text(saved, "state"), text(saved, "access") { + Some("signed_in"), Some(token) -> { + let fresh = case decode_field(saved, "expires", decode.int) { + Ok(expires) -> expires - clock.system_ms() > skew_ms + Error(Nil) -> True + } + case fresh, rejected { + True, None -> Ok(Some(token)) + True, Some(other) if other != token -> Ok(Some(token)) + _, _ -> Ok(None) + } + } + _, _ -> Error(reason(saved)) + } +} + +fn refreshed( + home: String, + name: String, + url: String, + rejected: Option(String), +) -> Result(Option(String), String) { + let run = fn() { + case record(home, name, url) { + None -> Ok(None) + Some(saved) -> + case usable(saved, rejected) { + Ok(Some(token)) -> Ok(Some(token)) + Error(reason) -> Error(reason) + Ok(None) -> refresh(home, name, url, saved, rejected) + } + } + } + case + file.with_lock_timeout(home, "mcp-oauth/" <> name, refresh_wait_ms, run) + { + Ok(answer) -> answer + Error(Nil) -> Error("the sign-in is still refreshing") + } +} + +fn refresh( + home: String, + name: String, + url: String, + saved: Object, + rejected: Option(String), +) -> Result(Option(String), String) { + case text(saved, "refresh") { + Some(refresh_token) -> { + let resource = + dict.get(saved, "resourceParameter") + |> result.unwrap(dynamic.string(url)) + let assert Ok(resource) = decode.run(resource, decode.string) + let form = [ + #("grant_type", "refresh_token"), + #("refresh_token", refresh_token), + #("resource", resource), + ] + case token_request(saved, form) { + Tokens(tokens) -> { + let next = with_tokens(saved, tokens, field(saved, "scope")) + update(home, name, url, fn(_) { next }) + Ok(text(next, "access")) + } + Refused(_) -> { + let reason = "the saved sign-in expired; sign in again" + update(home, name, url, fn(current) { needs_sign_in(current, reason) }) + Error(reason) + } + Unasked(reason) -> + // The authorization server could not be asked: a token that has + // not been refused yet is still worth sending. + case rejected, text(saved, "access") { + None, Some(token) -> Ok(Some(token)) + _, _ -> Error("could not refresh the sign-in: " <> reason) + } + } + } + None -> { + let reason = "the sign-in expired; sign in again" + update(home, name, url, fn(current) { needs_sign_in(current, reason) }) + Error(reason) + } + } +} + +/// Records what a 401 or 403 from the server says and returns the reason the +/// request cannot go on. A 401 to a server without a sign-in, or one whose +/// token was refused even after a refresh, needs sign-in. A 403 +/// insufficient_scope keeps the token and asks for the wider scope, the +/// union of what was asked before and what the challenge names (2026-07-28 +/// basic/authorization, "Step-Up Authorization Flow"). +pub fn challenged( + home: String, + name: String, + url: String, + status: Int, + header: String, +) -> String { + let challenge = parse_challenge(header) + let metadata = dict.get(challenge, "resource_metadata") |> option.from_result + let scope = dict.get(challenge, "scope") |> option.from_result + case status, dict.get(challenge, "error") { + 403, Ok("insufficient_scope") -> { + let wider = union(option.then(record(home, name, url), requested), scope) + let reason = + "the server needs wider access (" + <> wider + <> "); sign in again to grant it" + update(home, name, url, fn(current) { + current + |> dict.insert("stepUp", dynamic.string(wider)) + |> dict.insert("reason", dynamic.string(reason)) + |> with_challenge(metadata, None) + }) + reason + } + _, _ -> { + let reason = case option.then(record(home, name, url), text(_, "state")) { + Some("signed_in") -> + "the server refused the saved sign-in; sign in again" + Some("signed_out") -> "signed out" + _ -> "the server asks you to sign in" + } + update(home, name, url, fn(current) { + needs_sign_in(current, reason) |> with_challenge(metadata, scope) + }) + reason + } + } +} + +fn with_challenge( + saved: Object, + metadata: Option(String), + scope: Option(String), +) -> Object { + let keep = fn(saved, key, value) { + case value { + Some(value) -> dict.insert(saved, key, dynamic.string(value)) + None -> saved + } + } + saved + |> keep("resourceMetadata", metadata) + |> keep("challengeScope", scope) +} + +fn needs_sign_in(saved: Object, reason: String) -> Object { + saved + |> dict.drop(["access", "refresh", "expires"]) + |> dict.insert("state", dynamic.string("needs_sign_in")) + |> dict.insert("reason", dynamic.string(reason)) +} + +/// A record whose tokens are dropped by the user. What the server asked for +/// and the client it registered stay for the next sign-in. +pub fn signed_out(saved: Dynamic) -> Dynamic { + let saved = case decode.run(saved, object_decoder()) { + Ok(saved) -> + dict.drop(saved, ["access", "refresh", "expires", "reason", "label"]) + Error(_) -> dict.new() + } + saved + |> dict.insert("state", dynamic.string("signed_out")) + |> to_dynamic +} + +fn reason(saved: Object) -> String { + case text(saved, "state"), text(saved, "reason") { + Some("signed_out"), _ -> "signed out" + _, Some(reason) -> reason + _, None -> "the server asks you to sign in" + } +} + +/// The scope the last sign-in asked for or a challenge named. +fn requested(saved: Object) -> Option(String) { + ["stepUp", "scope", "challengeScope"] + |> list.find_map(fn(key) { text(saved, key) |> option.to_result(Nil) }) + |> option.from_result +} + +/// The words of `first` then those of `second` it lacks. +fn union(first: Option(String), second: Option(String)) -> String { + case first, second { + None, None -> "" + Some(first), None -> first + None, Some(second) -> second + Some(first), Some(second) -> { + let words = lexemes(first) + list.append( + words, + list.filter(lexemes(second), fn(word) { !list.contains(words, word) }), + ) + |> string.join(" ") + } + } +} + +fn lexemes(value: String) -> List(String) { + string.split(value, " ") |> list.filter(fn(word) { word != "" }) +} + +/// The `Bearer` parameters of a WWW-Authenticate value (RFC 6750 section 3, +/// RFC 9728 section 5.1), lower-cased names to unquoted values. +fn parse_challenge(header: String) -> Dict(String, String) { + let bearer = case patterns.captures(header, "(?i)\\bbearer\\b(.*)") { + Ok([[rest, ..], ..]) -> rest + _ -> "" + } + case + patterns.captures( + bearer, + "([A-Za-z_]+)\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^,\\s]*))", + ) + { + Ok(pairs) -> + list.fold(pairs, dict.new(), fn(found, groups) { + case list.append(groups, [""]) { + [key, quoted, token, ..] -> + dict.insert(found, string.lowercase(key), unquote(quoted, token)) + _ -> found + } + }) + Error(Nil) -> dict.new() + } +} + +fn unquote(quoted: String, token: String) -> String { + case quoted { + "" -> token + _ -> unescape(quoted, "") + } +} + +/// Each backslash-escaped character as itself. +fn unescape(rest: String, done: String) -> String { + case string.split_once(rest, "\\") { + Error(Nil) -> done <> rest + Ok(#(before, after)) -> + case string.pop_grapheme(after) { + Ok(#(escaped, after)) -> unescape(after, done <> before <> escaped) + Error(Nil) -> done <> before <> "\\" + } + } +} + +// ---- sign-in ------------------------------------------------------------ + +/// Everything a sign-in needs before the browser opens: the server's +/// protected resource metadata, its authorization server's metadata, the +/// scope to ask for and how albedo is known to that server. +pub fn discover(home: String, name: String) -> Result(Plan, String) { + answer("could not prepare the sign-in", fn() { + use url <- result.try(server_url(home, name)) + let saved = record(home, name, url) |> option.unwrap(dict.new()) + let named = field(saved, "resourceMetadata") + use resource <- result.try(protected_resource(url, named)) + use parameter <- result.try(resource_parameter( + url, + field(resource, "resource"), + )) + use issuer <- result.try( + case + decode_field( + resource, + "authorization_servers", + decode.list(decode.dynamic), + ) + { + Ok([first, ..]) -> + decode.run(first, decode.string) + |> result.replace_error(Failed( + "the server names no authorization server", + )) + _ -> Error(Failed("the server names no authorization server")) + }, + ) + use _ <- result.try(allowed_endpoint(url, issuer)) + use metadata <- result.try(authorization_server(url, issuer)) + use _ <- result.try( + case + decode_field( + metadata, + "code_challenge_methods_supported", + decode.list(decode.dynamic), + ) + { + Ok(methods) -> + case list.contains(methods, dynamic.string("S256")) { + True -> Ok(Nil) + False -> Error(no_pkce) + } + Error(Nil) -> Error(no_pkce) + }, + ) + use source <- result.try(client_source(home, name, metadata)) + use scope <- result.try(scope(saved, resource, metadata)) + Ok(Plan( + home:, + name:, + url:, + resource: parameter, + metadata_url: named, + issuer:, + metadata:, + client: source, + scope:, + )) + }) +} + +const no_pkce = + Failed("the authorization server does not support PKCE with S256") + +fn server_url(home: String, name: String) -> Result(String, Failure) { + use extensions <- result.try( + settings_documents.read(home, "extensions.json") + |> result.replace_error(Broken), + ) + use mcp <- result.try( + settings_documents.object(extensions, "mcp") |> result.replace_error(Broken), + ) + use servers <- result.try( + settings_documents.object(to_dynamic(mcp), "servers") + |> result.replace_error(Broken), + ) + case dict.get(servers, name) { + Error(Nil) -> Error(Failed("no MCP server is named " <> name)) + Ok(server) -> + case server == term.json_null() { + True -> Error(Failed("no MCP server is named " <> name)) + False -> + case decode.run(server, http_server_decoder()) { + Ok(url) -> Ok(url) + Error(_) -> Error(Failed("only HTTP MCP servers sign in")) + } + } + } +} + +fn http_server_decoder() -> decode.Decoder(String) { + use kind <- decode.field("type", decode.string) + use url <- decode.field("url", decode.string) + case kind { + "http" -> decode.success(url) + _ -> decode.failure(url, "HTTP server") + } +} + +/// The resource metadata the 401 named, else the well-known locations in the +/// spec's order: under the endpoint's path, then at the root. +fn protected_resource(url: String, named: Dynamic) -> Result(Object, Failure) { + use parsed <- result.try(located(url)) + let #(origin, path, _) = parsed + let root = origin <> "/.well-known/oauth-protected-resource" + let well_known = case path { + "" -> [root] + _ -> [root <> path, root] + } + use candidates <- result.try(case decode.run(named, decode.string) { + Ok(value) -> allowed_endpoint(url, value) |> result.replace([value]) + Error(_) -> Ok(well_known) + }) + first_document( + candidates, + fn(document) { + result.is_ok(decode_field( + document, + "authorization_servers", + decode.list(decode.dynamic), + )) + }, + "the server publishes no protected resource metadata", + ) +} + +/// The resource parameter: the metadata's `resource` when the server URL is +/// it or lies under it (RFC 9728 section 3.3), else the server URL. +fn resource_parameter( + url: String, + resource: Dynamic, +) -> Result(String, Failure) { + case resource == term.json_null(), decode.run(resource, decode.string) { + True, _ -> canonical(url) + _, Ok(resource) -> { + use canonical_resource <- result.try(canonical(resource)) + use server <- result.try(canonical(url)) + case + server == canonical_resource + || string.starts_with(server, canonical_resource <> "/") + { + True -> Ok(canonical_resource) + False -> Error(Failed("the server's metadata names another resource")) + } + } + _, Error(_) -> + Error(Failed("the server's metadata names no valid resource")) + } +} + +fn canonical(url: String) -> Result(String, Failure) { + case uri.parse(url) { + Ok(uri.Uri( + scheme: Some(scheme), + host: Some(host), + port: port, + path: path, + query: query, + .., + )) -> { + let query = case query { + Some(query) -> "?" <> query + None -> "" + } + Ok( + origin(string.lowercase(scheme), string.lowercase(host), port) + <> trim_slashes(path) + <> query, + ) + } + _ -> Error(Broken) + } +} + +/// A URL's origin, its path without trailing slashes, and the parsed URL. +fn located(url: String) -> Result(#(String, String, uri.Uri), Failure) { + case uri.parse(url) { + Ok( + uri.Uri(scheme: Some(scheme), host: Some(host), port: port, path:, ..) as parsed, + ) -> Ok(#(origin(scheme, host, port), trim_slashes(path), parsed)) + _ -> Error(Broken) + } +} + +fn trim_slashes(path: String) -> String { + let bytes = bit_array.from_string(path) + let size = bit_array.byte_size(bytes) + case bit_array.slice(bytes, size - 1, 1) { + Ok(<<"/">>) -> + bit_array.slice(bytes, 0, size - 1) + |> result.try(bit_array.to_string) + |> result.unwrap("") + |> trim_slashes + _ -> path + } +} + +fn origin(scheme: String, host: String, port: Option(Int)) -> String { + let host = case string.contains(host, ":") { + True -> "[" <> host <> "]" + False -> host + } + case port { + None -> scheme <> "://" <> host + Some(port) -> scheme <> "://" <> host <> ":" <> int.to_string(port) + } +} + +/// RFC 8414 metadata, then OpenID Connect discovery, as the spec orders them +/// for an issuer with and without a path. A document whose `issuer` is not +/// the one asked for is not used. +fn authorization_server( + url: String, + issuer: String, +) -> Result(Object, Failure) { + use #(origin, path, _) <- result.try(located(issuer)) + let candidates = case path { + "" -> [ + origin <> "/.well-known/oauth-authorization-server", + origin <> "/.well-known/openid-configuration", + ] + _ -> [ + origin <> "/.well-known/oauth-authorization-server" <> path, + origin <> "/.well-known/openid-configuration" <> path, + origin <> path <> "/.well-known/openid-configuration", + ] + } + use metadata <- result.try(first_document( + candidates, + fn(document) { field(document, "issuer") == dynamic.string(issuer) }, + "the authorization server publishes no metadata for its issuer", + )) + use _ <- result.try( + list.try_each( + ["authorization_endpoint", "token_endpoint", "registration_endpoint"], + fn(key) { + let value = field(metadata, key) + case decode.run(value, decode.string) { + Ok(endpoint) -> allowed_endpoint(url, endpoint) + Error(_) -> + case key == "registration_endpoint" && value == term.json_null() { + True -> Ok(Nil) + False -> + Error(Failed("the authorization server metadata has no " <> key)) + } + } + }, + ), + ) + Ok(metadata) +} + +fn first_document( + candidates: List(String), + valid: fn(Object) -> Bool, + reason: String, +) -> Result(Object, Failure) { + case candidates { + [] -> Error(Failed(reason)) + [candidate, ..rest] -> { + let document = case fetch_json("get", candidate, [], None) { + Ok(#(200, Some(document))) -> + decode.run(document, object_decoder()) |> option.from_result + _ -> None + } + case document { + Some(document) -> + case valid(document) { + True -> Ok(document) + False -> first_document(rest, valid, reason) + } + None -> first_document(rest, valid, reason) + } + } + } +} + +/// Authorization server endpoints must use https (2025-11-25 +/// basic/authorization, "Communication Security"). A server the user reaches +/// over plain http on a network they trust may name plain http ones too. +fn allowed_endpoint(url: String, endpoint: String) -> Result(Nil, Failure) { + case url_allowed(endpoint) { + True -> + case + string.starts_with(endpoint, "https://") + || string.starts_with(url, "http://") + { + True -> Ok(Nil) + False -> Error(Failed("the authorization server must use https")) + } + False -> Error(Failed("the authorization server named an invalid URL")) + } +} + +/// Whether `url` is an http or https URL with a host, and with neither user +/// information nor a fragment. +pub fn url_allowed(url: String) -> Bool { + case uri.parse(url) { + Ok(uri.Uri( + scheme: Some(scheme), + host: Some(host), + userinfo: None, + fragment: None, + .., + )) -> + host != "" + && { + scheme == "https" + && string.starts_with(url, "https:") + || scheme == "http" + && string.starts_with(url, "http:") + } + _ -> False + } +} + +/// The scope to ask for: a pending step-up, else the 401's scope, else the +/// resource's scopes_supported (2026-07-28 basic/authorization, "Scope +/// Selection Strategy"), with offline_access when the authorization server +/// lists it, so a refresh token may come back. +fn scope( + saved: Object, + resource: Object, + metadata: Object, +) -> Result(Option(String), Failure) { + use base <- result.try(case requested(saved) { + Some(scope) -> Ok(Some(scope)) + None -> + case + decode_field(resource, "scopes_supported", decode.list(decode.dynamic)) + { + Ok([_, ..] as scopes) -> + list.try_map(scopes, fn(scope) { decode.run(scope, decode.string) }) + |> result.map(fn(scopes) { Some(string.join(scopes, " ")) }) + |> result.replace_error(Broken) + _ -> Ok(None) + } + }) + let offline = + decode_field(metadata, "scopes_supported", decode.list(decode.dynamic)) + |> result.unwrap([]) + |> list.contains(dynamic.string("offline_access")) + Ok(case base, offline { + None, True -> Some("offline_access") + None, False -> None + Some(base), True -> Some(union(Some(base), Some("offline_access"))) + Some(base), False -> Some(base) + }) +} + +/// How albedo is known to the authorization server, in the spec's order +/// (2026-07-28 basic/authorization/client-registration): a client the user +/// configured for this server, then Dynamic Client Registration. Client ID +/// Metadata Documents come between them in the spec, but they need an https +/// URL albedo can host the document at, and a local daemon has none. +fn client_source( + home: String, + name: String, + metadata: Object, +) -> Result(ClientSource, Failure) { + case configured_client(home, name) { + Some(source) -> Ok(source) + None -> + case decode_field(metadata, "registration_endpoint", decode.string) { + Ok(endpoint) -> Ok(Register(endpoint)) + Error(Nil) -> + Error(Failed( + "the authorization server offers no client registration; configure a client id for this server", + )) + } + } +} + +fn configured_client(home: String, name: String) -> Option(ClientSource) { + let configured = { + use servers <- result.try( + settings_documents.mcp_secrets(home) |> result.replace_error(Nil), + ) + use secrets <- result.try(dict.get(servers, name)) + use configured <- result.try( + decode.run(secrets, decode.at(["oauthClient"], object_decoder())) + |> result.replace_error(Nil), + ) + case text(configured, "clientId") { + Some(id) if id != "" -> + Ok(Configured( + id, + dict.get(configured, "clientSecret") + |> result.unwrap(term.json_null()), + )) + _ -> Error(Nil) + } + } + option.from_result(configured) +} + +/// The authorize URL for one grant, registering albedo first when the +/// authorization server has no client for this redirect yet. +pub fn authorize(plan: Plan, grant: oauth.Grant) -> Result(String, String) { + answer("could not start the sign-in", fn() { + use registered <- result.try(registered(plan, grant.redirect)) + let query = + list.append( + [ + #("response_type", "code"), + #("client_id", registered.id), + #("redirect_uri", grant.redirect), + #("code_challenge", grant.challenge), + #("code_challenge_method", "S256"), + #("state", grant.state), + #("resource", plan.resource), + ], + case plan.scope { + Some(scope) -> [#("scope", scope)] + None -> [] + }, + ) + use endpoint <- result.try( + decode_field(plan.metadata, "authorization_endpoint", decode.string) + |> result.replace_error(Broken), + ) + let separator = case string.contains(endpoint, "?") { + True -> "&" + False -> "?" + } + Ok(endpoint <> separator <> form_query(query)) + }) +} + +/// The configured client, a registration this authorization server issued +/// for `redirect`, or a new one (RFC 7591), kept per issuer so another +/// authorization server never sees it. +fn registered(plan: Plan, redirect: String) -> Result(Registered, Failure) { + case plan.client { + Configured(id, secret) -> + Ok(Registered( + id, + secret, + dynamic.string(case secret == term.json_null() { + True -> "none" + False -> "client_secret_basic" + }), + )) + Register(endpoint) -> { + let saved = + record(plan.home, plan.name, plan.url) + |> option.then(fn(saved) { + decode.run( + saved |> to_dynamic, + decode.at(["registration"], object_decoder()), + ) + |> option.from_result + }) + |> option.then(fn(registration) { + case + field(registration, "issuer") == dynamic.string(plan.issuer) + && field(registration, "redirectUri") == dynamic.string(redirect) + { + True -> Some(registration) + False -> None + } + }) + case saved { + Some(registration) -> + case text(registration, "clientId") { + Some(id) -> + Ok(Registered( + id, + dict.get(registration, "clientSecret") + |> result.unwrap(term.json_null()), + dict.get(registration, "authMethod") + |> result.unwrap(dynamic.string("none")), + )) + None -> Error(Broken) + } + None -> register(plan, endpoint, redirect) + } + } + } +} + +fn register( + plan: Plan, + endpoint: String, + redirect: String, +) -> Result(Registered, Failure) { + let request = [ + #("client_name", dynamic.string("albedo")), + #("redirect_uris", dynamic.list([dynamic.string(redirect)])), + #( + "grant_types", + dynamic.list([ + dynamic.string("authorization_code"), + dynamic.string("refresh_token"), + ]), + ), + #("response_types", dynamic.list([dynamic.string("code")])), + #("token_endpoint_auth_method", dynamic.string("none")), + #("application_type", dynamic.string("native")), + ] + let request = case plan.scope { + Some(scope) -> [#("scope", dynamic.string(scope)), ..request] + None -> request + } + let body = request |> dict.from_list |> to_dynamic |> encode_json + case + fetch_json( + "post", + endpoint, + [], + Some(http.Body("application/json", bit_array.from_string(body))), + ) + { + Ok(#(status, Some(answer))) if status == 200 || status == 201 -> + case decode.run(answer, object_decoder()) { + Ok(answer) -> + case text(answer, "client_id") { + Some(id) -> { + let secret = case text(answer, "client_secret") { + Some(secret) -> dynamic.string(secret) + None -> term.json_null() + } + let method = case text(answer, "token_endpoint_auth_method") { + Some(method) -> method + None -> + case secret == term.json_null() { + True -> "none" + False -> "client_secret_basic" + } + } + let registration = + dict.from_list([ + #("issuer", dynamic.string(plan.issuer)), + #("redirectUri", dynamic.string(redirect)), + #("clientId", dynamic.string(id)), + #("clientSecret", secret), + #("authMethod", dynamic.string(method)), + ]) + update(plan.home, plan.name, plan.url, fn(current) { + dict.insert(current, "registration", to_dynamic(registration)) + }) + Ok(Registered(id, secret, dynamic.string(method))) + } + None -> + Error( + Failed(described( + "client registration", + status, + Some(to_dynamic(answer)), + )), + ) + } + Error(_) -> + Error(Failed(described("client registration", status, Some(answer)))) + } + Ok(#(status, answer)) -> + Error(Failed(described("client registration", status, answer))) + Error(reason) -> Error(Failed(reason)) + } +} + +/// Trades the authorization code for tokens and returns the credential the +/// sign-in stores. An `iss` in the response must be the issuer albedo asked +/// (RFC 9207 section 2.4), and one the server promised must be there. +pub fn exchange( + plan: Plan, + grant: oauth.Grant, + code: String, + iss: Option(String), +) -> Result(Dict(String, Dynamic), String) { + answer("could not finish the sign-in", fn() { + let promised = + field(plan.metadata, "authorization_response_iss_parameter_supported") + == dynamic.bool(True) + use _ <- result.try(case iss, promised { + Some(issuer), _ if issuer == plan.issuer -> Ok(Nil) + Some(_), _ -> + Error(Failed("the authorization response came from another issuer")) + None, True -> + Error(Failed("the authorization response did not name its issuer")) + None, False -> Ok(Nil) + }) + use registered <- result.try(registered(plan, grant.redirect)) + let client = + dict.from_list([ + #("tokenEndpoint", field(plan.metadata, "token_endpoint")), + #("clientId", dynamic.string(registered.id)), + #("clientSecret", registered.secret), + #("authMethod", registered.method), + ]) + let form = [ + #("grant_type", "authorization_code"), + #("code", code), + #("redirect_uri", grant.redirect), + #("code_verifier", grant.verifier), + #("resource", plan.resource), + ] + case token_request(client, form) { + Tokens(tokens) -> { + let base = + client + |> dict.insert("issuer", dynamic.string(plan.issuer)) + |> dict.insert("resource", dynamic.string(plan.url)) + |> dict.insert("resourceParameter", dynamic.string(plan.resource)) + |> dict.insert("resourceMetadata", plan.metadata_url) + let requested = case plan.scope { + Some(scope) -> dynamic.string(scope) + None -> term.json_null() + } + Ok(with_tokens(base, tokens, requested)) + } + Refused(reason) -> Error(Failed(reason)) + Unasked(reason) -> Error(Failed(reason)) + } + }) +} + +/// A credential with the token response folded in: the access token, a new +/// refresh token or the old one, when it expires, the granted scope, and the +/// account a token names, for "signed in as". +fn with_tokens(saved: Object, tokens: Object, requested: Dynamic) -> Object { + let expires = case decode_field(tokens, "expires_in", decode.int) { + Ok(seconds) if seconds > 0 -> dynamic.int(clock.system_ms() + seconds * 1000) + _ -> term.json_null() + } + let refresh = case text(tokens, "refresh_token") { + Some(refresh) -> dynamic.string(refresh) + None -> field(saved, "refresh") + } + let granted = case text(tokens, "scope") { + Some(scope) -> dynamic.string(scope) + None -> requested + } + let label = + account_label( + tokens, + field(saved, "label"), + dict.get(saved, "issuer") |> result.unwrap(dynamic.string("")), + ) + saved + |> dict.insert("state", dynamic.string("signed_in")) + |> dict.insert("access", field(tokens, "access_token")) + |> dict.insert("refresh", refresh) + |> dict.insert("expires", expires) + |> dict.insert("scope", granted) + |> dict.insert("label", label) + |> dict.drop(["reason", "stepUp"]) +} + +fn account_label( + tokens: Object, + previous: Dynamic, + issuer: Dynamic, +) -> Dynamic { + let named = + ["id_token", "access_token"] + |> list.filter_map(fn(key) { + text(tokens, key) |> option.to_result(Nil) |> result.try(jwt_claims) + }) + |> list.flat_map(fn(claims) { + list.filter_map(["email", "preferred_username", "name", "sub"], fn(key) { + case text(claims, key) { + Some(value) if value != "" -> Ok(value) + _ -> Error(Nil) + } + }) + }) + case named, decode.run(previous, decode.string) { + [name, ..], _ -> dynamic.string(text_scalars.take(name, 256)) + [], Ok(_) -> previous + [], Error(_) -> + case decode.run(issuer, decode.string) { + Ok(issuer_url) -> + case uri.parse(issuer_url) { + Ok(uri.Uri(host: Some(host), ..)) -> dynamic.string(host) + _ -> issuer + } + Error(_) -> issuer + } + } +} + +fn jwt_claims(token: String) -> Result(Object, Nil) { + case string.split(token, ".") { + [_, payload, _] -> { + use bytes <- result.try(bit_array.base64_url_decode(payload)) + json.parse_bits(bytes, object_decoder()) |> result.replace_error(Nil) + } + _ -> Error(Nil) + } +} + +/// The account a stored credential names: one per server, so a new sign-in +/// replaces the last. +pub fn account(name: String, credential: Dynamic) -> oauth.Account { + let label = + decode.run(credential, decode.at(["label"], decode.string)) + |> result.unwrap(name) + oauth.Account("mcp:" <> name, label, "MCP server " <> name, False) +} + +/// Creds with this server's signed-in credential in place, keeping the +/// registration an earlier sign-in made. The sign-in service calls it under +/// the settings lock. +pub fn signed_in(creds: Dynamic, name: String, credential: Dynamic) -> Dynamic { + let assert Ok(document) = decode.run(creds, object_decoder()) + let assert Ok(servers) = settings_documents.object(creds, "mcp") + let assert Ok(secrets) = + dict.get(servers, name) + |> result.unwrap(to_dynamic(dict.new())) + |> decode.run(object_decoder()) + let previous = + dict.get(secrets, "oauth") + |> result.try(fn(value) { + decode.run(value, object_decoder()) |> result.replace_error(Nil) + }) + |> result.unwrap(dict.new()) + let assert Ok(credential) = decode.run(credential, object_decoder()) + let kept = dict.take(previous, ["registration", "challengeScope"]) + let secrets = + dict.insert(secrets, "oauth", to_dynamic(dict.merge(kept, credential))) + let servers = dict.insert(servers, name, to_dynamic(secrets)) + dict.insert(document, "mcp", to_dynamic(servers)) |> to_dynamic +} + +// ---- token endpoint ----------------------------------------------------- + +fn token_request(client: Object, form: List(#(String, String))) -> TokenAnswer { + let assert Ok(endpoint) = decode_field(client, "tokenEndpoint", decode.string) + let assert Ok(id) = decode_field(client, "clientId", decode.string) + let method = + dict.get(client, "authMethod") |> result.unwrap(dynamic.string("none")) + let secret = text(client, "clientSecret") + let #(form, headers) = case decode.run(method, decode.string), secret { + Ok("client_secret_basic"), Some(secret) -> { + let basic = + bit_array.base64_encode( + bit_array.from_string( + form_component(id) <> ":" <> form_component(secret), + ), + True, + ) + #(form, [#("authorization", "Basic " <> basic)]) + } + Ok("client_secret_post"), Some(secret) -> #( + list.append(form, [#("client_id", id), #("client_secret", secret)]), + [], + ) + _, _ -> #(list.append(form, [#("client_id", id)]), []) + } + let body = + http.Body( + "application/x-www-form-urlencoded", + bit_array.from_string(form_query(form)), + ) + case fetch_json("post", endpoint, headers, Some(body)) { + Ok(#(200, Some(answer))) -> + case decode.run(answer, object_decoder()) { + Ok(tokens) -> + case text(tokens, "access_token") { + Some(_) -> + case + decode_field(tokens, "token_type", decode.string) + |> result.unwrap("bearer") + |> string.lowercase + { + "bearer" -> Tokens(tokens) + _ -> + Refused( + "the authorization server issued a token albedo cannot send", + ) + } + None -> Unasked(described("the token request", 200, Some(answer))) + } + Error(_) -> Unasked(described("the token request", 200, Some(answer))) + } + Ok(#(status, answer)) if status >= 400 && status < 500 -> + Refused(described("the token request", status, answer)) + Ok(#(status, answer)) -> + Unasked(described("the token request", status, answer)) + Error(reason) -> Unasked(reason) + } +} + +/// Fields as application/x-www-form-urlencoded, as OTP's +/// `uri_string:compose_query` writes them. +fn form_query(fields: List(#(String, String))) -> String { + fields + |> list.map(fn(field) { + form_component(field.0) <> "=" <> form_component(field.1) + }) + |> string.join("&") +} + +/// One form component: letters, digits, and `*-._` kept, a space as `+`, and +/// every other byte percent-encoded in upper case. A client id or secret in +/// HTTP Basic is encoded this way for OAuth (RFC 6749 section 2.3.1). +fn form_component(value: String) -> String { + form_bytes(bit_array.from_string(value), []) +} + +fn form_bytes(bytes: BitArray, done: List(String)) -> String { + case bytes { + <> -> { + let encoded = case byte { + 0x20 -> "+" + 0x2A | 0x2D | 0x2E | 0x5F -> ascii(byte) + _ if byte >= 0x30 && byte <= 0x39 -> ascii(byte) + _ if byte >= 0x41 && byte <= 0x5A -> ascii(byte) + _ if byte >= 0x61 && byte <= 0x7A -> ascii(byte) + _ -> "%" <> string.pad_start(int.to_base16(byte), 2, "0") + } + form_bytes(rest, [encoded, ..done]) + } + _ -> done |> list.reverse |> string.concat + } +} + +fn ascii(byte: Int) -> String { + bit_array.to_string(<>) |> result.unwrap("") +} + +fn described(what: String, status: Int, answer: Option(Dynamic)) -> String { + let error = + option.to_result(answer, Nil) + |> result.try(fn(answer) { + decode.run(answer, object_decoder()) |> result.replace_error(Nil) + }) + case + result.try(error, fn(answer) { + option.to_result(text(answer, "error"), Nil) + }) + { + Ok(error_code) -> { + let detail = case + result.try(error, fn(answer) { + option.to_result(text(answer, "error_description"), Nil) + }) + { + Ok(detail) -> ": " <> text_scalars.take(detail, 512) + Error(Nil) -> "" + } + what <> " was refused (" <> error_code <> detail <> ")" + } + Error(Nil) -> what <> " failed with HTTP " <> int.to_string(status) + } +} + +/// The status and decoded JSON body of one request, None for a body that is +/// not JSON, or why the server could not be asked. +fn fetch_json( + method: String, + url: String, + headers: List(#(String, String)), + body: Option(http.Body), +) -> Result(#(Int, Option(Dynamic)), String) { + case + http.request( + method, + url, + [#("accept", "application/json"), ..headers], + body, + http.Timeouts(fetch_ms, fetch_ms), + ) + { + Ok(http.Response(status, _, response)) -> + case bit_array.byte_size(response) <= max_body { + True -> + Ok(#( + status, + json.parse_bits(response, decode.dynamic) |> option.from_result, + )) + False -> Error("the answer was too large") + } + Error(_) -> { + let host = case uri.parse(url) { + Ok(uri.Uri(host: Some(host), ..)) -> host + _ -> url + } + Error("could not reach " <> host) + } + } +} + +// ---- creds.json --------------------------------------------------------- + +/// This server's sign-in record when it belongs to `url`. +fn record(home: String, name: String, url: String) -> Option(Object) { + { + use servers <- result.try( + settings_documents.mcp_secrets(home) |> result.replace_error(Nil), + ) + use secrets <- result.try(dict.get(servers, name)) + owned(secrets, url) + } + |> option.from_result +} + +/// The `oauth` record in one server's secrets when it belongs to `url`. +fn owned(secrets: Dynamic, url: String) -> Result(Object, Nil) { + use saved <- result.try( + decode.run(secrets, decode.at(["oauth"], object_decoder())) + |> result.replace_error(Nil), + ) + case text(saved, "resource") { + Some(resource) if resource == url -> Ok(saved) + _ -> Error(Nil) + } +} + +/// Replaces this server's record with `change(current)` under the settings +/// lock. A record for another URL is started afresh. +fn update( + home: String, + name: String, + url: String, + change: fn(Object) -> Object, +) -> Nil { + let _ = + settings_documents.with_lock(home, fn() { + use creds <- result.try(settings_documents.read(home, "creds.json")) + use document <- result.try( + decode.run(creds, object_decoder()) + |> result.replace_error("invalid settings"), + ) + use servers <- result.try(settings_documents.object(creds, "mcp")) + use secrets <- result.try( + dict.get(servers, name) + |> result.unwrap(to_dynamic(dict.new())) + |> decode.run(object_decoder()) + |> result.replace_error("invalid settings"), + ) + let current = case owned(to_dynamic(secrets), url) { + Ok(current) -> current + Error(Nil) -> + dict.from_list([ + #("resource", dynamic.string(url)), + #("state", dynamic.string("needs_sign_in")), + ]) + } + let next = change(current) + case next == current { + True -> Ok(Nil) + False -> { + let secrets = dict.insert(secrets, "oauth", to_dynamic(next)) + let servers = dict.insert(servers, name, to_dynamic(secrets)) + let document = dict.insert(document, "mcp", to_dynamic(servers)) + settings_documents.commit_group( + home, + dict.from_list([#("creds.json", to_dynamic(document))]), + ) + } + } + }) + Nil +} + +// ---- values ------------------------------------------------------------- + +/// Runs one entrypoint: a failure's reason, or `generic` for a value albedo +/// could not use or a crash. +fn answer( + generic: String, + run: fn() -> Result(a, Failure), +) -> Result(a, String) { + case protect.attempt(run) { + Ok(Ok(value)) -> Ok(value) + Ok(Error(Failed(reason))) -> Error(reason) + Ok(Error(Broken)) | Error(_) -> Error(generic) + } +} + +fn object_decoder() -> decode.Decoder(Object) { + decode.dict(decode.string, decode.dynamic) +} + +fn to_dynamic(value: Object) -> Dynamic { + value + |> dict.to_list + |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) + |> dynamic.properties +} + +fn encode_json(value: Dynamic) -> String { + types.encode_value(value) |> json.to_string +} + +/// A field's value, or null when it is absent. +fn field(value: Object, key: String) -> Dynamic { + dict.get(value, key) |> result.unwrap(term.json_null()) +} + +fn text(value: Object, key: String) -> Option(String) { + decode_field(value, key, decode.string) |> option.from_result +} + +fn decode_field( + value: Object, + key: String, + decoder: decode.Decoder(a), +) -> Result(a, Nil) { + dict.get(value, key) + |> result.try(fn(value) { + decode.run(value, decoder) |> result.replace_error(Nil) + }) +} diff --git a/src/albedo/harness/extensions/mcp/preparation.gleam b/src/albedo/harness/extensions/mcp/preparation.gleam index 1276cacda..0eed918e3 100644 --- a/src/albedo/harness/extensions/mcp/preparation.gleam +++ b/src/albedo/harness/extensions/mcp/preparation.gleam @@ -1,8 +1,11 @@ //// MCP preparation sequencing. Clients and connectors remain native resource //// authorities; a prepared bundle is published only after composition adoption. +import albedo/harness/capabilities import albedo/harness/extensions/mcp/catalogue +import albedo/harness/extensions/mcp/servers import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode import gleam/list import gleam/option.{type Option, None, Some} import gleam/result @@ -14,7 +17,8 @@ pub type Connector pub type Owners -pub type Preferences +pub type Preferences = + capabilities.Preferences pub type Catalogue = #(List(catalogue.Operation), catalogue.Summary) @@ -53,8 +57,8 @@ pub fn join( connect: fn(String, Dynamic, Dynamic, Owners) -> Result(#(Server, Catalogue), Failure), ) -> Result(Joined, Failure) { - let fingerprint = fingerprint(config, secrets) - case saved(cache.0(name, fingerprint)) { + let fingerprint = servers.fingerprint(config, secrets) + case catalogue.saved(cache.0(name, fingerprint)) { Some(catalogue) -> Ok(#( name, @@ -254,12 +258,6 @@ fn link_loop( } } -@external(erlang, "albedo_mcp", "fingerprint") -fn fingerprint(config: Dynamic, secrets: Dynamic) -> String - -@external(erlang, "albedo_mcp", "preparation_saved") -fn saved(value: Option(BitArray)) -> Option(Catalogue) - @external(erlang, "albedo_mcp", "preparation_save") fn save_cold( server: Server, @@ -277,12 +275,30 @@ fn configured_join( owners: Owners, ) -> Result(Joined, Failure) -@external(erlang, "albedo_mcp", "preparation_selected") +/// Whether a configured server joins this session: enabled in its settings +/// and not turned off among the session's capability choices. fn selected( name: String, config: Dynamic, preferences: Preferences, -) -> Result(Bool, String) +) -> Result(Bool, String) { + case decode.run(config, decode.dict(decode.dynamic, decode.dynamic)) { + Error(_) -> Error("MCP configuration is invalid") + Ok(_) -> { + let enabled = + decode.run(config, decode.at(["enabled"], decode.dynamic)) + |> result.unwrap(dynamic.bool(True)) + |> decode.run(decode.bool) + case enabled, capabilities.enabled(preferences, "mcp", name) { + Ok(True), Ok(True) -> Ok(True) + Ok(False), _ -> Ok(False) + _, Ok(False) -> Ok(False) + _, Error(reason) -> Error(reason) + Error(_), Ok(True) -> Error("MCP configuration is invalid") + } + } + } +} @external(erlang, "albedo_mcp", "close_joined") fn close_joined(joined: List(Joined)) -> Nil diff --git a/src/albedo/harness/extensions/mcp/secrets.gleam b/src/albedo/harness/extensions/mcp/secrets.gleam new file mode 100644 index 000000000..4ca971fd9 --- /dev/null +++ b/src/albedo/harness/extensions/mcp/secrets.gleam @@ -0,0 +1,55 @@ +//// Each MCP server's saved secrets. They never enter extension settings, +//// prompt context, or API responses. They live in the `mcp` section of +//// creds.json. A missing file means no saved secrets, and a file others can +//// read is an error. + +import albedo/harness/sdk/file_status +import albedo/harness/sdk/settings +import albedo/harness/sdk/settings_documents +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/erlang/atom +import gleam/int + +const max_bytes = 1_048_576 + +/// `name`'s secrets in this daemon's home. +pub fn server(name: String) -> Result(Dynamic, String) { + server_at(settings.home(), name) +} + +/// `name`'s secrets in `home`: an empty object when it has none. +pub fn server_at(home: String, name: String) -> Result(Dynamic, String) { + case file_status.link_status(file_status.join(home, "creds.json")) { + Error(file_status.Missing) -> Ok(empty()) + Ok(file_status.Status(file_status.Regular, size, mode)) + if size <= max_bytes + -> + case int.bitwise_and(mode, 0o077) { + 0 -> saved(home, name) + _ -> Error(unsafe_file) + } + _ -> Error(unsafe_file) + } +} + +const unsafe_file = "creds.json must be a regular 0600 file under ~/.albedo" + +fn saved(home: String, name: String) -> Result(Dynamic, String) { + case settings_documents.mcp_secrets(home) { + Ok(servers) -> + case dict.get(servers, name) { + Ok(secrets) -> Ok(secrets) + Error(Nil) -> Ok(empty()) + } + Error(reason) -> + case reason == atom.to_dynamic(atom.create("enoent")) { + True -> Ok(empty()) + False -> Error("invalid creds.json") + } + } +} + +fn empty() -> Dynamic { + dynamic.properties([]) +} diff --git a/src/albedo/harness/extensions/mcp/servers.gleam b/src/albedo/harness/extensions/mcp/servers.gleam new file mode 100644 index 000000000..f01c17a06 --- /dev/null +++ b/src/albedo/harness/extensions/mcp/servers.gleam @@ -0,0 +1,542 @@ +//// One configured MCP server's settings: name and URL rules, saved-settings +//// validation, the fingerprint that keys its saved catalogue, and the client +//// transport its configuration and secrets describe. Environment references +//// resolve when a transport is built, never during validation. + +import albedo/harness/extensions/mcp/client +import albedo/harness/extensions/mcp/oauth +import albedo/harness/sdk/digest +import albedo/harness/sdk/settings +import albedo/harness/sdk/term +import albedo/harness/sdk/term_codec +import gleam/bit_array +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string + +const default_startup_ms = 20_000 + +const default_call_ms = 60_000 + +const default_retry_ms = 30_000 + +/// The probe interval of servers whose settings name none, such as an +/// editor's. +pub fn default_retry() -> Int { + default_retry_ms +} + +/// Daemon variables a stdio server keeps. Every other one is unset. +const safe_environment = [ + "HOME", "PATH", "TMPDIR", "TEMP", "TMP", "SystemRoot", "WINDIR", +] + +const invalid_settings = "invalid MCP name, transport references, or credentials" + +/// Server names are 1 to 64 bytes of letters, digits, `_` and `-`, starting +/// with a letter or digit. +pub fn valid_name(name: String) -> Bool { + case bit_array.from_string(name) { + <> -> + string.byte_size(name) <= 64 + && alphanumeric(first) + && all_bytes(rest, fn(byte) { + alphanumeric(byte) || byte == 0x5F || byte == 0x2D + }) + _ -> False + } +} + +/// A timeout or retry in milliseconds: a whole number from 1 to 3,600,000. +pub fn positive_ms(value: Dynamic) -> Result(Int, Nil) { + case decode.run(value, decode.int) { + Ok(ms) if ms > 0 && ms <= 3_600_000 -> Ok(ms) + _ -> Error(Nil) + } +} + +/// The startup and call timeouts of a server's configuration. +pub fn timeouts(config: Dynamic) -> Result(#(Int, Int), Nil) { + use startup <- result.try( + positive_ms(member( + config, + "startupTimeoutMs", + dynamic.int(default_startup_ms), + )), + ) + use call <- result.try( + positive_ms(member(config, "callTimeoutMs", dynamic.int(default_call_ms))), + ) + Ok(#(startup, call)) +} + +/// Whether `url` is an http or https URL with a host, and with neither user +/// information nor a fragment. +pub fn url_allowed(url: String) -> Bool { + oauth.url_allowed(url) +} + +/// Names one server's configuration and credentials, so a saved catalogue +/// is only trusted for the setup that produced it. A sign-in's tokens change +/// on every refresh, so they are left out, and so is the `tools` class, +/// which changes how a catalogue is shown, not what it is. +pub fn fingerprint(config: Dynamic, secrets: Dynamic) -> String { + let assert Ok(config) = decode.run(config, native_map()) + let assert Ok(secrets) = decode.run(secrets, native_map()) + let server = dict.delete(config, dynamic.string("tools")) |> from_map + let stable = dict.delete(secrets, dynamic.string("oauth")) |> from_map + term_codec.encode_deterministic(#(server, stable)) + |> digest.sha256 + |> digest.hex +} + +/// Checks saved transport references and a secrets patch without resolving +/// environment variables or starting a client. +pub fn validate_settings( + name: String, + server: Option(Dynamic), + secret: Dynamic, +) -> Result(Nil, String) { + { + use <- check(valid_name(name)) + use _ <- result.try(case server { + None -> Ok(Nil) + Some(config) -> validate_server(config) + }) + use secret <- result.try(object(secret)) + dict.to_list(secret) + |> list.try_each(fn(entry) { validate_secret(entry.0, entry.1) }) + } + |> result.replace_error(invalid_settings) +} + +fn validate_server(config: Dynamic) -> Result(Nil, Nil) { + use fields <- result.try(object(config)) + let get = fn(key, default) { dict.get(fields, key) |> result.unwrap(default) } + use _ <- result.try( + decode.run(get("enabled", dynamic.bool(True)), decode.bool) + |> result.replace_error(Nil), + ) + use _ <- result.try( + list.try_each(["startupTimeoutMs", "callTimeoutMs"], fn(key) { + positive_ms(get(key, dynamic.int(default_call_ms))) + }), + ) + use _ <- result.try( + list.try_each(["args", "enabledTools", "disabledTools"], fn(key) { + let value = get(key, dynamic.list([])) + case key == "enabledTools" && value == term.json_null() { + True -> Ok(Nil) + False -> strings(value) |> result.replace(Nil) + } + }), + ) + use _ <- result.try(case text(get("type", term.json_null())) { + Ok("http") -> { + use url <- result.try(text(get("url", term.json_null()))) + check(url_allowed(url), fn() { Ok(Nil) }) + } + Ok("stdio") -> { + use command <- result.try(text(get("command", term.json_null()))) + check(command != "", fn() { Ok(Nil) }) + } + _ -> Error(Nil) + }) + use _ <- result.try( + list.try_each(["headers", "env"], fn(field) { + use references <- result.try(object(get(field, dynamic.properties([])))) + dict.to_list(references) + |> list.try_each(fn(entry) { + let #(target, reference) = entry + use <- check(valid_target(field, target)) + case environment_name(reference), text(reference) { + Ok(name), _ -> check(valid_env_name(name), fn() { Ok(Nil) }) + _, Ok(literal) -> + check(field != "headers" || !has_newline(literal), fn() { Ok(Nil) }) + _, _ -> Error(Nil) + } + }) + }), + ) + let variable = get("bearerTokenEnvVar", term.json_null()) + case variable == term.json_null() { + True -> Ok(Nil) + False -> { + use name <- result.try(text(variable)) + check(valid_env_name(name), fn() { Ok(Nil) }) + } + } +} + +fn validate_secret(field: String, value: Dynamic) -> Result(Nil, Nil) { + let null = value == term.json_null() + case field { + "bearerToken" if null -> Ok(Nil) + "bearerToken" -> { + use token <- result.try(text(value)) + check(!has_newline(token), fn() { Ok(Nil) }) + } + "oauth" -> object(value) |> result.replace(Nil) + "oauthClient" -> { + use client <- result.try(object(value)) + use id <- result.try(dict.get(client, "clientId")) + text(id) |> result.replace(Nil) + } + "headers" | "env" if null -> Ok(Nil) + "headers" | "env" -> { + use changes <- result.try(object(value)) + dict.to_list(changes) + |> list.try_each(fn(entry) { + let #(target, change) = entry + use <- check(valid_target(field, target)) + case change == term.json_null(), text(change) { + True, _ -> Ok(Nil) + False, Ok(literal) -> + check(field != "headers" || !has_newline(literal), fn() { Ok(Nil) }) + False, Error(Nil) -> Error(Nil) + } + }) + } + _ -> Error(Nil) + } +} + +fn valid_target(field: String, target: String) -> Bool { + case field { + "headers" -> valid_header(target) + _ -> valid_env_name(target) + } +} + +/// The client's transport. An HTTP server without an authorization header +/// of its own may sign in with OAuth. A stdio server runs through the +/// launcher with only the safe daemon variables and its own. +pub fn transport( + name: String, + config: Dynamic, + secrets: Dynamic, +) -> Result(client.Transport, Nil) { + use fields <- result.try(object(config)) + let get = fn(key, default) { dict.get(fields, key) |> result.unwrap(default) } + let kind = text(get("type", term.json_null())) + case kind { + Ok("http") -> { + use url <- result.try(text(get("url", term.json_null()))) + use <- check(url != "" && url_allowed(url)) + use headers <- result.try(http_headers(fields, secrets)) + let authorised = + list.any(headers, fn(header) { + string.lowercase(header.0) == "authorization" + }) + Ok( + client.Http(url, headers, case authorised { + True -> None + False -> Some(oauth.auth(settings.home(), name, url)) + }), + ) + } + Ok("stdio") -> { + use command <- result.try(text(get("command", term.json_null()))) + use <- check(command != "") + use arguments <- result.try(strings(get("args", dynamic.list([])))) + let cwd = get("cwd", term.json_null()) + use cwd <- result.try(case cwd == term.json_null() { + True -> Ok("") + False -> text(cwd) + }) + use given <- result.try(environment( + get("env", dynamic.properties([])), + member(secrets, "env", dynamic.properties([])), + )) + use python <- result.try(executable("python3")) + use launcher <- result.try(launcher()) + use command <- result.try(executable(command)) + Ok(client.Stdio( + python, + [launcher, cwd, command, ..arguments], + stdio_environment(given, safe_environment), + )) + } + _ -> Error(Nil) + } +} + +/// The configured headers, resolved, then the saved ones, then a bearer +/// token. A later header replaces an earlier one of the same name. +fn http_headers( + config: Dict(String, Dynamic), + secrets: Dynamic, +) -> Result(List(#(String, String)), Nil) { + use raw <- result.try(object( + dict.get(config, "headers") |> result.unwrap(dynamic.properties([])), + )) + use resolved <- result.try( + dict.fold(raw, Ok([]), fn(headers, name, reference) { + use headers <- result.try(headers) + use value <- result.try(reference_value(reference)) + set_header(headers, name, value) + }), + ) + use saved <- result.try( + object(member(secrets, "headers", dynamic.properties([]))), + ) + use headers <- result.try( + dict.fold(saved, Ok(resolved), fn(headers, name, value) { + use headers <- result.try(headers) + use value <- result.try(text(value)) + set_header(headers, name, value) + }), + ) + let variable = + dict.get(config, "bearerTokenEnvVar") |> result.unwrap(term.json_null()) + let token = member(secrets, "bearerToken", term.json_null()) + case variable == term.json_null(), token == term.json_null() { + True, True -> Ok(headers) + False, True -> { + use variable <- result.try(text(variable)) + use token <- result.try(required_env(variable)) + set_header(headers, "authorization", "Bearer " <> token) + } + True, False -> + case text(token) { + Ok(token) if token != "" -> + set_header(headers, "authorization", "Bearer " <> token) + _ -> Error(Nil) + } + False, False -> Error(Nil) + } +} + +fn set_header( + headers: List(#(String, String)), + name: String, + value: String, +) -> Result(List(#(String, String)), Nil) { + use <- check(valid_header(name) && !has_newline(value)) + Ok([#(name, value), ..list.filter(headers, fn(header) { header.0 != name })]) +} + +/// The variables a stdio server is given: its configured ones, resolved, +/// then its saved ones. +fn environment( + raw: Dynamic, + saved: Dynamic, +) -> Result(List(#(String, String)), Nil) { + use raw <- result.try(object(raw)) + use saved <- result.try(object(saved)) + use added <- result.try( + dict.fold(raw, Ok([]), fn(given, target, reference) { + use given <- result.try(given) + use value <- result.try(reference_value(reference)) + Ok([#(target, value), ..given]) + }), + ) + use saved <- result.try( + dict.fold(saved, Ok([]), fn(given, target, value) { + use given <- result.try(given) + use value <- result.try(text(value)) + use <- check(valid_env_name(target)) + Ok([#(target, value), ..given]) + }), + ) + Ok(list.append(added, saved)) +} + +/// A literal value, or the value of the daemon variable `{"env": name}` +/// names, which must be set. +fn reference_value(reference: Dynamic) -> Result(String, Nil) { + case environment_name(reference) { + Ok(name) -> required_env(name) + Error(Nil) -> text(reference) + } +} + +fn environment_name(reference: Dynamic) -> Result(String, Nil) { + case object(reference) { + Ok(fields) -> + case dict.to_list(fields) { + [#("env", name)] -> text(name) + _ -> Error(Nil) + } + Error(Nil) -> Error(Nil) + } +} + +fn required_env(name: String) -> Result(String, Nil) { + variable(name) +} + +fn valid_header(name: String) -> Bool { + case bit_array.from_string(name) { + <<>> -> False + bytes -> + all_bytes(bytes, fn(byte) { + alphanumeric(byte) + || list.contains( + [ + 0x21, + 0x23, + 0x24, + 0x25, + 0x26, + 0x27, + 0x2A, + 0x2B, + 0x2E, + 0x5E, + 0x5F, + 0x60, + 0x7C, + 0x7E, + 0x2D, + ], + byte, + ) + }) + } +} + +fn valid_env_name(name: String) -> Bool { + case bit_array.from_string(name) { + <> -> + { letter(first) || first == 0x5F } + && all_bytes(rest, fn(byte) { alphanumeric(byte) || byte == 0x5F }) + _ -> False + } +} + +fn has_newline(value: String) -> Bool { + string.contains(value, "\n") +} + +fn letter(byte: Int) -> Bool { + byte >= 0x41 && byte <= 0x5A || byte >= 0x61 && byte <= 0x7A +} + +fn alphanumeric(byte: Int) -> Bool { + letter(byte) || byte >= 0x30 && byte <= 0x39 +} + +fn all_bytes(bytes: BitArray, valid: fn(Int) -> Bool) -> Bool { + case bytes { + <> -> valid(byte) && all_bytes(rest, valid) + _ -> True + } +} + +fn check(condition: Bool, next: fn() -> Result(a, Nil)) -> Result(a, Nil) { + case condition { + True -> next() + False -> Error(Nil) + } +} + +fn object(value: Dynamic) -> Result(Dict(String, Dynamic), Nil) { + decode.run(value, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error(Nil) +} + +fn native_map() -> decode.Decoder(Dict(Dynamic, Dynamic)) { + decode.dict(decode.dynamic, decode.dynamic) +} + +fn from_map(fields: Dict(Dynamic, Dynamic)) -> Dynamic { + fields |> dict.to_list |> dynamic.properties +} + +fn text(value: Dynamic) -> Result(String, Nil) { + decode.run(value, decode.string) |> result.replace_error(Nil) +} + +fn strings(value: Dynamic) -> Result(List(String), Nil) { + decode.run(value, decode.list(decode.string)) |> result.replace_error(Nil) +} + +/// A map member, or `default` when the value is a map without it. +fn member(value: Dynamic, key: String, default: Dynamic) -> Dynamic { + decode.run(value, decode.at([key], decode.dynamic)) |> result.unwrap(default) +} + +@external(erlang, "albedo_mcp_stdio", "variable") +fn variable(name: String) -> Result(String, Nil) + +@external(erlang, "albedo_mcp_stdio", "environment") +fn stdio_environment( + given: List(#(String, String)), + keep: List(String), +) -> client.Environment + +@external(erlang, "albedo_mcp_stdio", "executable") +fn executable(command: String) -> Result(String, Nil) + +@external(erlang, "albedo_mcp_stdio", "launcher") +fn launcher() -> Result(String, Nil) + +/// The configured servers in name order, and the retry interval, from the +/// `mcp` section as JSON. +pub fn configured_candidates( + config: String, +) -> Result(#(List(#(String, Dynamic)), Int), Nil) { + let decoder = { + use servers <- decode.optional_field( + "servers", + dict.new(), + decode.dict(decode.string, decode.dynamic), + ) + use retry <- decode.optional_field( + "retryMs", + dynamic.int(default_retry_ms), + decode.dynamic, + ) + decode.success(#(servers, retry)) + } + use #(servers, retry) <- result.try( + json.parse(config, decoder) |> result.replace_error(Nil), + ) + use retry <- result.try(positive_ms(retry)) + let candidates = + dict.to_list(servers) + |> list.sort(fn(left, right) { string.compare(left.0, right.0) }) + Ok(#(candidates, retry)) +} + +/// An editor's stdio servers from its JSON list, each run in `workspace` +/// with its literal `env` values passed as secrets. +pub fn overlay_candidates( + servers: String, + workspace: String, +) -> Result(List(#(String, Dynamic, Dynamic)), Nil) { + let variable = { + use name <- decode.field("name", decode.string) + use value <- decode.field("value", decode.string) + decode.success(#(dynamic.string(name), dynamic.string(value))) + } + let candidate = { + use name <- decode.field("name", decode.string) + use command <- decode.field("command", decode.string) + use arguments <- decode.field("args", decode.list(decode.dynamic)) + use environment <- decode.field("env", decode.list(decode.dynamic)) + let literal = + list.filter_map(environment, fn(entry) { + decode.run(entry, variable) |> result.replace_error(Nil) + }) + |> dict.from_list + |> dict.to_list + |> dynamic.properties + let config = + dynamic.properties([ + #(dynamic.string("type"), dynamic.string("stdio")), + #(dynamic.string("command"), dynamic.string(command)), + #(dynamic.string("args"), dynamic.list(arguments)), + #(dynamic.string("cwd"), dynamic.string(workspace)), + ]) + let secrets = dynamic.properties([#(dynamic.string("env"), literal)]) + decode.success(#(name, config, secrets)) + } + json.parse(servers, decode.list(candidate)) |> result.replace_error(Nil) +} diff --git a/src/albedo/harness/extensions/mcp/sign_in.gleam b/src/albedo/harness/extensions/mcp/sign_in.gleam index 1fab34757..21d68d2b4 100644 --- a/src/albedo/harness/extensions/mcp/sign_in.gleam +++ b/src/albedo/harness/extensions/mcp/sign_in.gleam @@ -1,10 +1,10 @@ //// Sign-ins for HTTP MCP servers that ask for OAuth. The daemon's sign-in -//// service (`oauth_flows`) runs the browser half; `albedo_mcp_oauth` -//// discovers the server's authorization server, registers albedo with it, -//// and trades the code for tokens it keeps in creds.json. +//// service (`oauth_flows`) runs the browser half; `mcp/oauth` discovers the +//// server's authorization server, registers albedo with it, and trades the +//// code for tokens it keeps in creds.json. +import albedo/harness/extensions/mcp/oauth as mcp_oauth import albedo/harness/sdk/oauth -import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} import gleam/option.{type Option, None, Some} import gleam/result @@ -15,9 +15,6 @@ import gleam/result /// `http://127.0.0.1:33418/callback`. const callback_port = 33_418 -/// What discovery found for one server: opaque to Gleam. -type Plan - /// The sign-in for `provider` when it names an MCP server as `mcp:`. pub fn resolve( home: String, @@ -33,7 +30,7 @@ pub fn resolve( /// in place, keeping the registration an earlier sign-in made. pub fn keep(creds: Dynamic, provider: String, credential: Dynamic) -> Dynamic { case provider { - "mcp:" <> name -> native_signed_in(creds, name, credential) + "mcp:" <> name -> mcp_oauth.signed_in(creds, name, credential) _ -> creds } } @@ -41,11 +38,11 @@ pub fn keep(creds: Dynamic, provider: String, credential: Dynamic) -> Dynamic { /// A saved sign-in record with its tokens dropped. What the server asked for /// and the client it registered stay for the next sign-in. pub fn signed_out(record: Dynamic) -> Dynamic { - native_signed_out(record) + mcp_oauth.signed_out(record) } fn login(home: String, name: String) -> Result(oauth.Login, String) { - use plan <- result.map(native_discover(home, name)) + use plan <- result.map(mcp_oauth.discover(home, name)) oauth.Login( "mcp:" <> name, "sign in to " <> name, @@ -53,38 +50,11 @@ fn login(home: String, name: String) -> Result(oauth.Login, String) { oauth.Service, "mcp:" <> name, oauth.Callback("127.0.0.1", callback_port, "/callback", False), - fn(grant) { native_authorize(plan, grant) }, + fn(grant) { mcp_oauth.authorize(plan, grant) }, fn(grant, code, _progress) { - native_exchange(plan, grant, code, grant.issuer) + mcp_oauth.exchange(plan, grant, code, grant.issuer) }, - fn(credential) { native_account(name, credential) }, + fn(credential) { mcp_oauth.account(name, credential) }, None, ) } - -@external(erlang, "albedo_mcp_oauth", "discover") -fn native_discover(home: String, name: String) -> Result(Plan, String) - -@external(erlang, "albedo_mcp_oauth", "authorize") -fn native_authorize(plan: Plan, grant: oauth.Grant) -> Result(String, String) - -@external(erlang, "albedo_mcp_oauth", "exchange") -fn native_exchange( - plan: Plan, - grant: oauth.Grant, - code: String, - issuer: Option(String), -) -> Result(Dict(String, Dynamic), String) - -@external(erlang, "albedo_mcp_oauth", "account") -fn native_account(name: String, credential: Dynamic) -> oauth.Account - -@external(erlang, "albedo_mcp_oauth", "signed_in") -fn native_signed_in( - creds: Dynamic, - name: String, - credential: Dynamic, -) -> Dynamic - -@external(erlang, "albedo_mcp_oauth", "signed_out") -fn native_signed_out(record: Dynamic) -> Dynamic diff --git a/src/albedo/harness/sdk/file_status.gleam b/src/albedo/harness/sdk/file_status.gleam new file mode 100644 index 000000000..778218ac4 --- /dev/null +++ b/src/albedo/harness/sdk/file_status.gleam @@ -0,0 +1,64 @@ +//// What a path names, without following a final symbolic link, for checks +//// that a secret file is a private regular file before reading it. + +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom +import gleam/result + +pub type Kind { + Regular + Directory + Symlink + Device + Other +} + +pub type Status { + Status(kind: Kind, size: Int, mode: Int) +} + +pub type StatusError { + /// Nothing exists at the path. + Missing + /// The path could not be inspected, for example for want of permission. + Unreadable +} + +/// The kind, size in bytes, and permission bits of `path` itself. A symbolic +/// link reports `Symlink`, not what it points to. +pub fn link_status(path: String) -> Result(Status, StatusError) { + case read_link_info(path) { + Ok(info) -> decode.run(info, decoder()) |> result.replace_error(Unreadable) + Error(reason) -> + case atom.to_dynamic(atom.create("enoent")) == reason { + True -> Error(Missing) + False -> Error(Unreadable) + } + } +} + +/// `name` joined to `directory` as one path. +@external(erlang, "filename", "join") +pub fn join(directory: String, name: String) -> String + +/// Fields 1, 2, and 7 of OTP's `#file_info{}` record: size, type, and mode. +fn decoder() -> decode.Decoder(Status) { + use size <- decode.field(1, decode.int) + use kind <- decode.field(2, atom.decoder()) + use mode <- decode.field(7, decode.int) + decode.success(Status( + case atom.to_string(kind) { + "regular" -> Regular + "directory" -> Directory + "symlink" -> Symlink + "device" -> Device + _ -> Other + }, + size, + mode, + )) +} + +@external(erlang, "file", "read_link_info") +fn read_link_info(path: String) -> Result(Dynamic, Dynamic) diff --git a/src/albedo/harness/sdk/log.gleam b/src/albedo/harness/sdk/log.gleam new file mode 100644 index 000000000..3c02cdf48 --- /dev/null +++ b/src/albedo/harness/sdk/log.gleam @@ -0,0 +1,10 @@ +//// Messages for the daemon's log. Never include secrets or tokens. + +/// Logs `message` at warning level. +pub fn warning(message: String) -> Nil { + logger_warning("~ts", [message]) + Nil +} + +@external(erlang, "logger", "warning") +fn logger_warning(format: String, arguments: List(String)) -> a diff --git a/src/albedo/harness/sdk/settings_documents.gleam b/src/albedo/harness/sdk/settings_documents.gleam new file mode 100644 index 000000000..82045f530 --- /dev/null +++ b/src/albedo/harness/sdk/settings_documents.gleam @@ -0,0 +1,67 @@ +//// Whole settings documents under a home, such as `extensions.json` and +//// `creds.json`, for features that keep their own section of one. Reads and +//// group commits use the settings store, so a commit replaces its documents +//// together and recovers after a crash. Hold `with_lock` across a read and the +//// commit that depends on it. + +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/result + +/// The JSON object saved as `file` under `home`, or an empty object when the +/// file is absent. A file that is not a readable JSON object is an error. +pub fn read(home: String, file: String) -> Result(Dynamic, String) { + guarded(fn() { Ok(native_read(home, file)) }) +} + +/// The object under `key` in a document, or an empty one when it is absent. +/// A value there that is not an object is an error. +pub fn object( + document: Dynamic, + key: String, +) -> Result(Dict(String, Dynamic), String) { + case decode.run(document, decode.at([key], decode.dynamic)) { + Error(_) -> Ok(dict.new()) + Ok(value) -> + decode.run(value, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error("invalid settings section") + } +} + +/// Runs `run` while holding the settings lock of `home`. A nested call in the +/// same process keeps the outer lock. +@external(erlang, "albedo_settings_store", "with_lock") +pub fn with_lock( + home: String, + run: fn() -> Result(a, String), +) -> Result(a, String) + +/// Replaces each named document with its JSON value, all together. +pub fn commit_group( + home: String, + documents: Dict(String, Dynamic), +) -> Result(Nil, String) { + guarded(fn() { + native_commit_group(home, documents) + Ok(Nil) + }) +} + +/// The `mcp` section of `creds.json`: each server's saved secrets. An absent +/// file has none. +pub fn mcp_secrets(home: String) -> Result(Dict(String, Dynamic), Dynamic) { + native_mcp(home) +} + +@external(erlang, "albedo_settings_store", "read") +fn native_read(home: String, file: String) -> Dynamic + +@external(erlang, "albedo_settings_store", "commit_group") +fn native_commit_group(home: String, documents: Dict(String, Dynamic)) -> a + +@external(erlang, "albedo_settings_store", "guarded") +fn guarded(run: fn() -> Result(a, String)) -> Result(a, String) + +@external(erlang, "albedo_credentials", "mcp") +fn native_mcp(home: String) -> Result(Dict(String, Dynamic), Dynamic) diff --git a/src/albedo/harness/sdk/term_codec.gleam b/src/albedo/harness/sdk/term_codec.gleam new file mode 100644 index 000000000..1a6b831e8 --- /dev/null +++ b/src/albedo/harness/sdk/term_codec.gleam @@ -0,0 +1,37 @@ +//// Erlang's external term format, for caches and fingerprints whose bytes +//// earlier daemons wrote or compare. Use JSON for new persisted data. + +import albedo/harness/sdk/protect +import gleam/dynamic.{type Dynamic} +import gleam/result + +type EncodeOption { + Deterministic +} + +type DecodeOption { + Safe +} + +/// `value` in the external term format. +@external(erlang, "erlang", "term_to_binary") +pub fn encode(value: a) -> BitArray + +/// `value` in the external term format with map keys in a fixed order, so +/// equal values give equal bytes within one OTP release. +pub fn encode_deterministic(value: a) -> BitArray { + term_to_binary(value, [Deterministic]) +} + +/// The term `bytes` encode. Bytes that are not an external term, or that +/// would create atoms or functions this node does not know, are an error. +pub fn decode_safe(bytes: BitArray) -> Result(Dynamic, Nil) { + protect.attempt(fn() { binary_to_term(bytes, [Safe]) }) + |> result.replace_error(Nil) +} + +@external(erlang, "erlang", "term_to_binary") +fn term_to_binary(value: a, options: List(EncodeOption)) -> BitArray + +@external(erlang, "erlang", "binary_to_term") +fn binary_to_term(bytes: BitArray, options: List(DecodeOption)) -> Dynamic diff --git a/test/harness/albedo_mcp_catalogue_test_support.erl b/test/harness/albedo_mcp_catalogue_test_support.erl index 633c51599..3b235171a 100644 --- a/test/harness/albedo_mcp_catalogue_test_support.erl +++ b/test/harness/albedo_mcp_catalogue_test_support.erl @@ -1,5 +1,6 @@ -module(albedo_mcp_catalogue_test_support). -export([legacy_v2_cache/0]). +-define(CATALOGUE, 'albedo@harness@extensions@mcp@catalogue'). %% A pre-migration cache, including header paths and every summary kind. This %% guards upgrades and rollback, which live discovery scenarios cannot cover. @@ -23,15 +24,19 @@ legacy_v2_cache() -> prompts => [#{<<"name">> => <<"review">>, <<"description">> => <<"Review code">>}] }, Legacy = {2, [Operation], Summary}, - {ok, Catalogue = {Operations, _}} = albedo_mcp_catalogue:saved({some, term_to_binary(Legacy)}), - Legacy = binary_to_term(albedo_mcp_catalogue:encode_catalogue(Catalogue), [safe]), + {some, Catalogue = {Operations, _}} = ?CATALOGUE:saved({some, term_to_binary(Legacy)}), + Legacy = binary_to_term(?CATALOGUE:encode(Catalogue), [safe]), [#{<<"name">> := <<"mcp_legacy_echo_1234567890">>, <<"parameters">> := Schema}] = - json:decode('albedo@harness@extensions@mcp@catalogue':definitions(Operations)), + json:decode(?CATALOGUE:definitions(Operations)), Schema = maps:get(schema, Operation), [{operation, _, _, _, _, _, _, _, Headers}] = Operations, [{<<"Mcp-Param-Count">>, <<"7">>}] = 'albedo@harness@extensions@mcp@param_headers':values( Headers, #{<<"nested">> => #{<<"count">> => 7}} ), - none = albedo_mcp_catalogue:saved({some, <<"not an external term">>}), - none = albedo_mcp_catalogue:saved({some, term_to_binary({1, [], <<>>})}), + none = ?CATALOGUE:saved({some, <<"not an external term">>}), + none = ?CATALOGUE:saved({some, term_to_binary({1, [], <<>>})}), + none = ?CATALOGUE:saved({some, term_to_binary({2, [Operation], Summary, extra})}), + none = ?CATALOGUE:saved({some, term_to_binary([2, [Operation], Summary])}), + none = ?CATALOGUE:saved({some, term_to_binary({2, [Operation#{kind => other}], Summary})}), + none = ?CATALOGUE:saved(none), true. diff --git a/test/harness/albedo_mcp_ownership_test_support.erl b/test/harness/albedo_mcp_ownership_test_support.erl index b4ead5566..330882d72 100644 --- a/test/harness/albedo_mcp_ownership_test_support.erl +++ b/test/harness/albedo_mcp_ownership_test_support.erl @@ -5,11 +5,12 @@ cold_ownership/0, connector_attempts/0, gate_link/7, - gate_discover/1, + gate_discover/4, gate_transfer/2 ]). -define(CLIENT, 'albedo@harness@extensions@mcp@client'). -define(CONNECTOR, 'albedo@harness@extensions@mcp@connector'). +-define(CATALOGUE, 'albedo@harness@extensions@mcp@catalogue'). -define(NATIVE, albedo_mcp_ownership_copy). %% Cached preparation must return without opening a transport. Connector @@ -263,7 +264,7 @@ connector_attempts() -> patch({attribute, L, module, _}) -> {attribute, L, module, ?NATIVE}; -patch({call, L, {remote, R, {atom, A, albedo_mcp_catalogue}, {atom, B, discover}}, Args}) -> +patch({call, L, {remote, R, {atom, A, ?CATALOGUE}, {atom, B, discover_guarded}}, Args}) -> {call, L, {remote, R, {atom, A, ?MODULE}, {atom, B, gate_discover}}, patch(Args)}; patch({call, L, {remote, R, {atom, A, ?CLIENT}, {atom, B, transfer}}, Args}) -> {call, L, {remote, R, {atom, A, ?MODULE}, {atom, B, gate_transfer}}, patch(Args)}; @@ -274,17 +275,17 @@ patch(List) when is_list(List) -> [patch(Item) || Item <- List]; patch(Value) -> Value. -gate_discover(Server) -> +gate_discover(Name, Client, Timeout, Config) -> case get(mcp_discovery_controller) of undefined -> ok; Controller -> - Controller ! {discovery_gate, self(), maps:get(pid, Server)}, + Controller ! {discovery_gate, self(), ?CLIENT:pid(Client)}, receive continue -> ok end end, - albedo_mcp_catalogue:discover(Server). + ?CATALOGUE:discover_guarded(Name, Client, Timeout, Config). interrupted_discovery(Owner) -> Controller = self(), diff --git a/test/harness/mcp_credentials_test.gleam b/test/harness/mcp_credentials_test.gleam index db7b4b739..0a524caff 100644 --- a/test/harness/mcp_credentials_test.gleam +++ b/test/harness/mcp_credentials_test.gleam @@ -1,4 +1,5 @@ // Private regular-file validation guards symlink and permissions attacks on MCP credentials. +import albedo/harness/extensions/mcp/secrets import gleam/dynamic import gleeunit/should @@ -17,8 +18,9 @@ fn link(base: String, source: String, path: String) -> Nil @external(erlang, "albedo_skills_test_support", "cleanup") fn cleanup(root: String) -> Nil -@external(erlang, "albedo_mcp_credentials", "server_at") -fn secret(home: String, name: String) -> Result(dynamic.Dynamic, String) +fn secret(home: String, name: String) -> Result(dynamic.Dynamic, String) { + secrets.server_at(home, name) +} pub fn credentials_require_private_regular_file_test() -> Nil { let #(root, _, home) = fixture() diff --git a/test/harness/mcp_url_test.gleam b/test/harness/mcp_url_test.gleam index fa75715f7..0f5045199 100644 --- a/test/harness/mcp_url_test.gleam +++ b/test/harness/mcp_url_test.gleam @@ -1,8 +1,10 @@ // MCP URL validation blocks embedded credentials and unsupported schemes even on trusted networks. +import albedo/harness/extensions/mcp/servers import gleeunit/should -@external(erlang, "albedo_mcp", "url_allowed") -fn allowed(url: String) -> Bool +fn allowed(url: String) -> Bool { + servers.url_allowed(url) +} pub fn mcp_http_trusted_network_test() -> Nil { allowed("http://100.64.0.19:8787/mcp") |> should.be_true -- knotmirror 0.0.1