Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bind-socket-handshake-origin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Bind embedded client WebSocket authentication to the actual browser handshake origin instead of a client-supplied socket parameter. Reject missing, malformed, duplicate, or unapproved handshake origins while preserving dynamically approved embedding sites and localhost development.
5 changes: 5 additions & 0 deletions .changeset/characterize-lost-mcp-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Add integration coverage for an ambiguous MCP write outcome after a lost response and reconnect. This characterizes the replay risk; it does not change recovery behavior.
5 changes: 5 additions & 0 deletions .changeset/decline-mcp-input-required.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Recognize valid MCP input-required tool responses and report a controlled tool failure instead of treating them as final output. Do not retry or retain opaque server state.
9 changes: 9 additions & 0 deletions .changeset/harden-mcp-test-fixtures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@frontman/bindings": patch
"@frontman-ai/frontman-client": patch
"@frontman-ai/frontman-protocol": patch
---

Add MCP subscription acknowledgments and validate notification filters. Decline state-only interim tool results through the existing error-result path instead of crashing the server channel.

Centralize Phoenix, Vitest, and Sentry bindings. Strengthen MCP regression tests and fix ACP and Sentry test fixtures.
5 changes: 5 additions & 0 deletions .changeset/mcp-configurable-retry-budget.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Add validated, caller-configured attempt and elapsed-time budgets for future MCP retry coordination. No retry defaults or automatic dispatch are enabled.
5 changes: 5 additions & 0 deletions .changeset/mcp-retry-admission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Add a backend MRTR retry admission policy with explicit permission and finite caller-supplied budgets. Automatic dispatch remains disabled pending replay and cancellation lifecycle integration.
8 changes: 8 additions & 0 deletions .changeset/quiet-subscription-streams.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@frontman-ai/frontman-client": patch
"@frontman/frontman-server-assets": patch
---

Handle browser MCP subscriptions with validated filters, correlated acknowledgments, cancellation, and attachment teardown. Accept MCP server notification envelopes in Phoenix without treating them as tool responses. Browser change-event categories remain unsupported; Phoenix does not open subscriptions automatically.

Cancel and complete active subscriptions before intentional session teardown. Drop request state without replay after transport loss. Reject request ID reuse while tool calls remain pending or suspended.
8 changes: 8 additions & 0 deletions .changeset/short-browsers-signal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@frontman-ai/frontman-protocol": patch
"@frontman-ai/frontman-client": patch
"@frontman-ai/client": patch
"@frontman-ai/astro-browser": patch
---

Pass request-scoped cancellation signals through browser MCP execution and local tool interfaces. Cancellation and transport teardown signal running tools without treating abort as proof of rollback. Non-cooperative tools may still return their actual result.
6 changes: 6 additions & 0 deletions .changeset/structured-tool-output.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@frontman-ai/frontman-protocol": patch
"@frontman/frontman-server-assets": patch
---

Deliver structured-only MCP tool results to the model, including arrays, scalars, and explicit JSON null. Preserve original text and image blocks and avoid appending structured JSON when an existing text block already contains equivalent serialized JSON. Extend opaque result constructors to accept arbitrary JSON while keeping dictionary-based helpers compatible.
5 changes: 5 additions & 0 deletions .changeset/tidy-rivers-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman-ai/frontman-client": patch
---

Allow relay tool requests to accept a request-scoped abort signal without aborting sibling calls or the relay connection. Connection teardown still aborts every request. Aborting a request does not establish whether an external write took effect.
17 changes: 17 additions & 0 deletions apps/frontman_server/lib/frontman_server/protocols/json_rpc.ex
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,23 @@ defmodule FrontmanServer.Protocols.JsonRpc do

def parse_response(_), do: {:error, :invalid_message}

@doc """
Parses MCP server responses and notifications, never server-initiated requests.
Notification IDs must be absent, not null, and params must be an object when present.
"""
def parse_server_message(%{"method" => _} = message) do
with {:ok, {:notification, _, params}} = notification <- parse(message),
false <- Enum.any?(["id", "result", "error"], &Map.has_key?(message, &1)),
true <- is_map(params) do
notification
else
{:error, reason} -> {:error, reason}
_invalid_envelope -> {:error, :invalid_message}
end
end

def parse_server_message(message), do: parse_response(message)

defp extract_id(%{"id" => id}), do: {:ok, id}
defp extract_id(_), do: {:error, :invalid_message}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
defmodule FrontmanServer.Protocols.MCP.RetryBudget do
@moduledoc """
Caller-configured finite limits for one logical operation, including its initial attempt.
No defaults or dispatch permission. The executor must enforce the same total deadline
while executing or waiting; checking only between attempts cannot bound a blocked call.
Elapsed milliseconds must come from a monotonic clock anchored at operation start.
"""
@enforce_keys [:attempts_max, :elapsed_ms_max]
defstruct [:attempts_max, :elapsed_ms_max, attempts: 1, elapsed_ms: 0]

@opaque t :: %__MODULE__{
attempts_max: pos_integer(),
elapsed_ms_max: pos_integer(),
attempts: pos_integer(),
elapsed_ms: non_neg_integer()
}

@spec new(term(), term()) :: {:ok, t()} | {:error, :invalid_budget}
def new(attempts_max, elapsed_ms_max)
when is_integer(attempts_max) and attempts_max > 0 and
is_integer(elapsed_ms_max) and elapsed_ms_max > 0,
do: {:ok, %__MODULE__{attempts_max: attempts_max, elapsed_ms_max: elapsed_ms_max}}

def new(_attempts_max, _elapsed_ms_max), do: {:error, :invalid_budget}

@spec advance(t(), term()) ::
{:ok, t()} | {:error, :invalid_elapsed | :retry_exhausted}
def advance(%__MODULE__{} = budget, elapsed_ms)
when is_integer(elapsed_ms) and elapsed_ms >= budget.elapsed_ms do
cond do
budget.attempts >= budget.attempts_max -> {:error, :retry_exhausted}
elapsed_ms >= budget.elapsed_ms_max -> {:error, :retry_exhausted}
true -> {:ok, %{budget | attempts: budget.attempts + 1, elapsed_ms: elapsed_ms}}
end
end

def advance(%__MODULE__{}, _elapsed_ms), do: {:error, :invalid_elapsed}
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
defmodule FrontmanServer.Protocols.MCP.RetryPolicy do
@moduledoc """
Pure admission policy for a future MRTR coordinator, not dispatch authorization.
Caller supplies budgets; attempts include the initial request, elapsed time is monotonic.
Permission must come from trusted operation policy, never remote tool hints.
"""

@type observation ::
:acknowledged_interim
| :cancelled
| :outcome_unknown
| :unsupported_input
| :protocol_failure
@type permission :: :authorized | :denied
@type decision ::
:request_continuation
| {:stop,
:cancelled
| :outcome_unknown
| :unsupported_input
| :protocol_failure
| :retry_not_permitted
| :retry_exhausted}

@spec decide(
observation(),
permission(),
pos_integer(),
pos_integer(),
non_neg_integer(),
pos_integer()
) :: decision()
def decide(observation, permission, attempts, attempts_max, elapsed_ms, elapsed_ms_max)
when observation in [
:acknowledged_interim,
:cancelled,
:outcome_unknown,
:unsupported_input,
:protocol_failure
] and permission in [:authorized, :denied] do
validate_budget!(attempts, attempts_max, elapsed_ms, elapsed_ms_max)

case {observation, permission} do
{:acknowledged_interim, :denied} ->
{:stop, :retry_not_permitted}

{:acknowledged_interim, :authorized} ->
cond do
attempts >= attempts_max -> {:stop, :retry_exhausted}
elapsed_ms >= elapsed_ms_max -> {:stop, :retry_exhausted}
true -> :request_continuation
end

{reason, _permission} ->
{:stop, reason}
end
end

defp validate_budget!(attempts, attempts_max, elapsed_ms, elapsed_ms_max)
when is_integer(attempts) and attempts > 0 and
is_integer(attempts_max) and attempts_max > 0 and
is_integer(elapsed_ms) and elapsed_ms >= 0 and
is_integer(elapsed_ms_max) and elapsed_ms_max > 0,
do: :ok
end
61 changes: 61 additions & 0 deletions apps/frontman_server/lib/frontman_server/protocols/mcp/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
defmodule FrontmanServer.Protocols.MCP.Schema do
@moduledoc false

alias FrontmanServer.Protocols.MCP

@schema_dir Path.expand("../../../../../../libs/frontman-protocol/schemas/mcp", __DIR__)
@discover_result_path Path.join(@schema_dir, "discoverResult.json")
@tools_list_result_path Path.join(@schema_dir, "toolsListResult.json")
Expand All @@ -20,6 +22,16 @@ defmodule FrontmanServer.Protocols.MCP.Schema do
@tools_list_result @tools_list_result_path |> File.read!() |> Jason.decode!() |> JSV.build!()
@call_tool_result @call_tool_result_path |> File.read!() |> Jason.decode!() |> JSV.build!()

@state_only_input_required JSV.build!(%{
"type" => "object",
"properties" => %{
"resultType" => %{"const" => "input_required"},
"requestState" => %{"type" => "string"},
"_meta" => %{"type" => "object"}
},
"required" => ["resultType", "requestState"]
})

def validate_discover_result(result), do: validate(result, @discover_result)

def validate_tools_list_result(result) do
Expand All @@ -41,8 +53,16 @@ defmodule FrontmanServer.Protocols.MCP.Schema do
end
end

def validate_call_tool_result(%{"resultType" => "input_required"} = result)
when not is_map_key(result, "inputRequests"),
do: validate(result, @state_only_input_required)

def validate_call_tool_result(result), do: validate(result, @call_tool_result)

def validate_call_tool_result(%{"resultType" => "input_required"} = result, _output_schema)
when not is_map_key(result, "inputRequests"),
do: validate_call_tool_result(result)

def validate_call_tool_result(%{"isError" => true} = result, output_schema)
when is_map(output_schema) and not is_map_key(result, "structuredContent"),
do: validate_call_tool_result(result)
Expand All @@ -61,6 +81,47 @@ defmodule FrontmanServer.Protocols.MCP.Schema do

def validate_call_tool_result(result, nil), do: validate_call_tool_result(result)

@doc """
Recognizes MRTR interims before validating final tool output.

No optional input capabilities are advertised by this client, so nonempty
inputRequests violate the negotiated contract. Opaque state is only type-checked.
"""
def resolve_call_tool_result(result, output_schema \\ nil)

def resolve_call_tool_result(%{"resultType" => "input_required"} = result, _schema) do
with true <- map_size(Map.take(result, ["inputRequests", "requestState"])) > 0,
true <- valid_request_state?(result),
true <- valid_input_requests?(result),
true <- valid_result_meta?(result) do
{:ok,
MCP.tool_result_error(
"MCP tool requires additional input (input_required); Frontman declines MRTR retry."
)}
else
_invalid -> :error
end
end

def resolve_call_tool_result(result, output_schema) do
case validate_call_tool_result(result, output_schema) do
:ok -> {:ok, result}
:error -> :error
end
end

defp valid_request_state?(%{"requestState" => state}), do: is_binary(state)
defp valid_request_state?(_result), do: true

defp valid_input_requests?(%{"inputRequests" => requests}) when is_map(requests),
do: map_size(requests) == 0

defp valid_input_requests?(%{"inputRequests" => _requests}), do: false
defp valid_input_requests?(_result), do: true

defp valid_result_meta?(%{"_meta" => meta}), do: is_map(meta)
defp valid_result_meta?(_result), do: true

defp schema_nodes_remaining(_value, _depth, 0), do: :error

defp schema_nodes_remaining(scalar, _depth, nodes) when not (is_map(scalar) or is_list(scalar)),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Frontman Server
# Copyright (C) 2025 Frontman AI
#
# Licensed under the AGPL-3.0 - see LICENSE for details.
# Additional terms apply - see AI-SUPPLEMENTARY-TERMS.md

defmodule FrontmanServer.Protocols.MCP.ToolOutput do
@moduledoc """
Validated complete tool output. Structured JSON null is distinct from absence.

Persisted historical results omit the discriminator and are treated as complete.
Explicit interim results never become tool output.
"""

alias FrontmanServer.Protocols.MCP.Schema

@enforce_keys [:content, :structured_content, :is_error]
defstruct [:content, :structured_content, :is_error]

@opaque t :: %__MODULE__{
content: [map()],
structured_content: :absent | {:present, Jason.Encoder.t()},
is_error: boolean()
}

@spec new(map(), map() | nil) :: {:ok, t()} | :error
def new(result, output_schema \\ nil) when is_map(result) do
result = Map.put_new(result, "resultType", "complete")

with %{"resultType" => "complete"} <- result,
:ok <- Schema.validate_call_tool_result(result, output_schema) do
{:ok,
%__MODULE__{
content: Map.fetch!(result, "content"),
structured_content: structured_content(result),
is_error: Map.get(result, "isError", false)
}}
else
_invalid -> :error
end
end

@doc """
Keeps original blocks in order and appends structured JSON unless a text block
already parses to the same JSON value. Prose is never treated as equivalent.
"""
def content_blocks(%__MODULE__{content: content, structured_content: :absent}),
do: content

def content_blocks(%__MODULE__{content: content, structured_content: {:present, value}}) do
case Enum.any?(content, &equivalent_json_text?(&1, value)) do
true -> content
false -> content ++ [%{"type" => "text", "text" => Jason.encode!(value)}]
end
end

defp structured_content(result) do
case Map.fetch(result, "structuredContent") do
{:ok, value} -> {:present, value}
:error -> :absent
end
end

defp equivalent_json_text?(%{"type" => "text", "text" => text}, value) do
case Jason.decode(text) do
{:ok, decoded} -> decoded == value
{:error, _error} -> false
end
end

defp equivalent_json_text?(_block, _value), do: false
end
9 changes: 7 additions & 2 deletions apps/frontman_server/lib/frontman_server/tasks/interaction.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ defmodule FrontmanServer.Tasks.Interaction do
]

alias FrontmanServer.CurrentPageContext
alias FrontmanServer.Protocols.MCP.ToolOutput
alias FrontmanServer.Tasks.Interaction
alias SwarmAi.Message, as: SwarmMessage
alias SwarmAi.Message.ContentPart, as: SwarmContentPart
Expand Down Expand Up @@ -1202,8 +1203,12 @@ defmodule FrontmanServer.Tasks.Interaction do
defp text_parts(text), do: [SwarmContentPart.text(text)]

@doc "Projects MCP tool-result content into Swarm content parts."
def tool_result_content_parts(%{"content" => content}) when is_list(content) do
Enum.map(content, &tool_result_content_part/1)
def tool_result_content_parts(%{"content" => content} = result) when is_list(content) do
{:ok, output} = ToolOutput.new(result)

output
|> ToolOutput.content_blocks()
|> Enum.map(&tool_result_content_part/1)
end

defp tool_result_content_part(%{"type" => "text", "text" => text}),
Expand Down
Loading
Loading