Clients take a flow's id or key: one resolver in the SDK, id first, explicit id:/key:, a warning for reads and a refusal for changes when a name means two flows, deleted flows found by their last key; sync creates by POST, retries a create race through the drift checks and reports the id; MCP gets create_flow and resolves every flow argument with the caller's token; displays show flow_name; an engine from before ids is named as such

This commit is contained in:
2026-11-02 19:39:14 +01:00
parent fd637e0f1e
commit 53916d869b
20 changed files with 816 additions and 147 deletions
+165 -55
View File
@@ -8,19 +8,24 @@ means an agent cannot do anything a person could not do in the browser.
The caller's token rides along on every hop, so the API sees the agent's own
identity rather than some service account.
A tool takes a flow by its id or its key, resolved by `fluksio.sdk.resolve`
from the flows the caller can list, and calls the API with the id.
"""
from __future__ import annotations
import logging
from contextvars import ContextVar
from typing import Any
from typing import Annotated, Any
import httpx
from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
from mcp.server.mcpserver import MCPServer
from pydantic import Field
from fluksio.sdk.client import seg as _seg
from fluksio.sdk.resolve import Resolved, Unresolved, resolve
logger = logging.getLogger(__name__)
@@ -126,6 +131,80 @@ async def _call(method: str, path: str, **kwargs: Any) -> Any:
return response.json()
async def _resolve(
flow: str, *, mutation: bool = False, history: bool = False
) -> Resolved | dict[str, Any]:
"""The flow *flow* names, or the error to hand back.
Read from what the caller may list, with the caller's token, so nothing
is resolved that the API would not show them. ``history`` counts deleted
flows too, under the key their runs last had.
"""
listing = await _call("GET", "/flows/")
if "error" in listing:
return dict(listing)
flows = [(str(row["id"]), str(row["name"])) for row in listing.get("data") or []]
if history:
overview = await _call("GET", "/runs/overview")
if isinstance(overview, dict):
return overview
flows += [
(str(row["flow"]), str(row.get("flow_name") or row["flow"]))
for row in overview
]
try:
return resolve(flow, flows, mutation=mutation)
except Unresolved as exc:
return {"error": str(exc)}
def _warned(answer: Any, found: Resolved) -> Any:
"""*answer*, saying which flow was taken when the name could mean two."""
if not found.warning:
return answer
if isinstance(answer, dict):
return {**answer, "warning": found.warning}
return {"result": answer, "warning": found.warning}
async def _on_flow(
flow: str, method: str, tail: str = "", *, mutation: bool, **kwargs: Any
) -> Any:
"""One call to ``/flows/<id><tail>`` for the flow *flow* names.
``mutation`` is whether the call changes anything, which a name two flows
answer to is refused for rather than guessed.
"""
found = await _resolve(flow, mutation=mutation)
if not isinstance(found, Resolved):
return found
answer = await _call(method, f"/flows/{_seg(found.id)}{tail}", **kwargs)
return _warned(answer, found)
async def _narrowed(flow: str | None, path: str, params: dict[str, Any]) -> Any:
"""A history read at *path*, narrowed to the flow *flow* names when it
names one, a deleted one included."""
if not flow:
return await _call("GET", path, params=params)
found = await _resolve(flow, history=True)
if not isinstance(found, Resolved):
return found
params["flow"] = found.id
return _warned(await _call("GET", path, params=params), found)
#: Every tool's *flow* argument, described where an agent reads the schema.
FlowArg = Annotated[
str,
Field(
description=(
"The flow's id or its key. Write id:<x> or key:<x> when one flow's "
"id is another's key."
)
),
]
# -----------------------------------------------------------------------------
# Reading
# -----------------------------------------------------------------------------
@@ -138,13 +217,14 @@ async def list_flows() -> Any:
@mcp.tool()
async def get_flow(name: str) -> Any:
async def get_flow(flow: FlowArg) -> Any:
"""One flow: its definition, the state of its nodes, and its problems.
The definition is the working copy — unpublished edits included — which is
what to base a change on.
what to base a change on. It carries the flow's ``id`` and its key,
``name``.
"""
return await _call("GET", f"/flows/{_seg(name)}")
return await _on_flow(flow, "GET", mutation=False)
@mcp.tool()
@@ -154,21 +234,21 @@ async def list_node_types() -> Any:
@mcp.tool()
async def get_node_source(name: str, node_id: str) -> Any:
async def get_node_source(flow: FlowArg, node_id: str) -> Any:
"""The Python source of one node."""
return await _call("GET", f"/flows/{_seg(name)}/nodes/{_seg(node_id)}/source")
return await _on_flow(flow, "GET", f"/nodes/{_seg(node_id)}/source", mutation=False)
@mcp.tool()
async def get_flow_state(name: str) -> Any:
async def get_flow_state(flow: FlowArg) -> Any:
"""The last value seen on every message of a flow."""
return await _call("GET", f"/flows/{_seg(name)}/state")
return await _on_flow(flow, "GET", "/state", mutation=False)
@mcp.tool()
async def get_message_history(name: str, message: str) -> Any:
async def get_message_history(flow: FlowArg, message: str) -> Any:
"""Recent numeric values of one message, oldest first."""
return await _call("GET", f"/flows/{_seg(name)}/history/{_seg(message)}")
return await _on_flow(flow, "GET", f"/history/{_seg(message)}", mutation=False)
@mcp.tool()
@@ -216,21 +296,36 @@ async def get_graph() -> Any:
@mcp.tool()
async def save_flow(name: str, definition: dict[str, Any]) -> Any:
"""Save a flow as an unpublished draft.
async def create_flow(definition: dict[str, Any]) -> Any:
"""Create a new flow, as an unpublished draft.
``definition`` is a flow document like the one `get_flow` returns under
``definition``. Its ``name`` is the new flow's key, which no other flow
may hold. The server gives the flow its id, so an ``id`` or ``version`` in
the document is ignored; the answer carries both. Change an existing flow
with `save_flow` instead.
"""
document = {k: v for k, v in definition.items() if k not in ("id", "version")}
return await _call("POST", "/flows/", json=document)
@mcp.tool()
async def save_flow(flow: FlowArg, definition: dict[str, Any]) -> Any:
"""Save changes to an existing flow as an unpublished draft.
``definition`` is a whole flow document — the shape `get_flow` returns
under ``definition``. It must carry the ``version`` that was read, so an
edit someone else made in between is refused rather than overwritten; on a
conflict, read the flow again and reapply the change.
conflict, read the flow again and reapply the change. Its ``name``, the
key, cannot change here. A new flow is `create_flow`.
Nothing here reaches the engine until `publish_flow`.
"""
return await _call("PUT", f"/flows/{_seg(name)}", json=definition)
return await _on_flow(flow, "PUT", mutation=True, json=definition)
@mcp.tool()
async def save_node_source(name: str, node_id: str, code: str) -> Any:
async def save_node_source(flow: FlowArg, node_id: str, code: str) -> Any:
"""Save a node's Python source and report whether it compiles.
A node defines ``process(...)``, taking one argument per input port and
@@ -238,35 +333,39 @@ async def save_node_source(name: str, node_id: str, code: str) -> Any:
or dropped there adds or drops the input port or setting in the draft,
which moves its version on: read the flow again before saving it.
"""
return await _call(
"PUT", f"/flows/{_seg(name)}/nodes/{_seg(node_id)}/source", json={"code": code}
return await _on_flow(
flow,
"PUT",
f"/nodes/{_seg(node_id)}/source",
mutation=True,
json={"code": code},
)
@mcp.tool()
async def publish_flow(name: str, version: int) -> Any:
async def publish_flow(flow: FlowArg, version: int) -> Any:
"""Deploy a flow's unpublished changes: this is what puts them live."""
return await _call(
"POST", f"/flows/{_seg(name)}/publish", json={"version": version}
return await _on_flow(
flow, "POST", "/publish", mutation=True, json={"version": version}
)
@mcp.tool()
async def discard_draft(name: str) -> Any:
async def discard_draft(flow: FlowArg) -> Any:
"""Throw unpublished changes away and go back to what is running."""
return await _call("POST", f"/flows/{_seg(name)}/discard-draft")
return await _on_flow(flow, "POST", "/discard-draft", mutation=True)
@mcp.tool()
async def delete_flow(name: str) -> Any:
async def delete_flow(flow: FlowArg) -> Any:
"""Delete a flow and the code of its nodes."""
return await _call("DELETE", f"/flows/{_seg(name)}")
return await _on_flow(flow, "DELETE", mutation=True)
@mcp.tool()
async def validate_flow(name: str) -> Any:
async def validate_flow(flow: FlowArg) -> Any:
"""What would keep this flow from running: loops, unconnected inputs."""
return await _call("POST", f"/flows/{_seg(name)}/validate")
return await _on_flow(flow, "POST", "/validate", mutation=False)
# -----------------------------------------------------------------------------
@@ -275,57 +374,59 @@ async def validate_flow(name: str) -> Any:
@mcp.tool()
async def run_flow(name: str, inputs: dict[str, Any] | None = None) -> Any:
async def run_flow(flow: FlowArg, inputs: dict[str, Any] | None = None) -> Any:
"""Run every node of a flow once and return the resulting state.
With unpublished changes this runs the draft, so a change can be tried
before it is published.
"""
return await _call(
"POST", f"/flows/{_seg(name)}/run", json={"inputs": inputs or {}}
return await _on_flow(
flow, "POST", "/run", mutation=True, json={"inputs": inputs or {}}
)
@mcp.tool()
async def trigger_node(
name: str, node_id: str, values: dict[str, Any] | None = None
flow: FlowArg, node_id: str, values: dict[str, Any] | None = None
) -> Any:
"""Feed values into one node and run everything downstream of it."""
return await _call(
return await _on_flow(
flow,
"POST",
f"/flows/{_seg(name)}/nodes/{_seg(node_id)}/trigger",
f"/nodes/{_seg(node_id)}/trigger",
mutation=True,
json={"values": values or {}},
)
@mcp.tool()
async def start_flow(name: str) -> Any:
async def start_flow(flow: FlowArg) -> Any:
"""Let the engine run this flow: subscriptions, schedules and webhooks."""
return await _call("POST", f"/flows/{_seg(name)}/start")
return await _on_flow(flow, "POST", "/start", mutation=True)
@mcp.tool()
async def stop_flow(name: str) -> Any:
async def stop_flow(flow: FlowArg) -> Any:
"""Take a flow off the engine. Nothing of it stays subscribed or scheduled."""
return await _call("POST", f"/flows/{_seg(name)}/stop")
return await _on_flow(flow, "POST", "/stop", mutation=True)
@mcp.tool()
async def pause_flow(name: str) -> Any:
async def pause_flow(flow: FlowArg) -> Any:
"""Hold a flow's nodes while its incoming values keep arriving."""
return await _call("POST", f"/flows/{_seg(name)}/pause")
return await _on_flow(flow, "POST", "/pause", mutation=True)
@mcp.tool()
async def resume_flow(name: str) -> Any:
async def resume_flow(flow: FlowArg) -> Any:
"""Let a paused flow carry on, running whatever was held back."""
return await _call("POST", f"/flows/{_seg(name)}/resume")
return await _on_flow(flow, "POST", "/resume", mutation=True)
@mcp.tool()
async def cancel_node(name: str, node_id: str) -> Any:
async def cancel_node(flow: FlowArg, node_id: str) -> Any:
"""Stop a node's code while it is running. Nothing to stop is not an error."""
return await _call("POST", f"/flows/{_seg(name)}/nodes/{_seg(node_id)}/cancel")
return await _on_flow(flow, "POST", f"/nodes/{_seg(node_id)}/cancel", mutation=True)
# -----------------------------------------------------------------------------
@@ -360,36 +461,45 @@ async def get_health() -> Any:
return await _call("GET", "/observability/summary")
#: The optional flow a history question is narrowed to.
FlowFilter = Annotated[
str | None,
Field(
description=(
"Only this flow: its id or its key, or the key it had before it was "
"deleted. Write id:<x> or key:<x> when the name could mean two."
)
),
]
@mcp.tool()
async def get_metrics(
flow: str | None = None, node: str | None = None, hours: int = 24
flow: FlowFilter = None, node: str | None = None, hours: int = 24
) -> Any:
"""Executions, errors and timings per minute over the last few hours."""
"""Executions, errors and timings per minute over the last few hours.
``node`` is ``<flow key>.<node id>``.
"""
params: dict[str, Any] = {"hours": hours}
if flow:
params["flow"] = flow
if node:
params["node"] = node
return await _call("GET", "/observability/timeseries", params=params)
return await _narrowed(flow, "/observability/timeseries", params)
@mcp.tool()
async def list_failures(flow: str | None = None, limit: int = 50) -> Any:
async def list_failures(flow: FlowFilter = None, limit: int = 50) -> Any:
"""Recent failures with their tracebacks, newest first."""
params: dict[str, Any] = {"kind": "failure", "limit": limit}
if flow:
params["flow"] = flow
return await _call("GET", "/observability/events", params=params)
return await _narrowed(flow, "/observability/events", params)
@mcp.tool()
async def list_runs(flow: str | None = None, limit: int = 50) -> Any:
async def list_runs(flow: FlowFilter = None, limit: int = 50) -> Any:
"""Recent cascades: what triggered them, how long they took, how they ended.
A page of rows plus the total number matching, which says whether the limit
cut anything off.
"""
params: dict[str, Any] = {"limit": limit}
if flow:
params["flow"] = flow
return await _call("GET", "/observability/runs", params=params)
return await _narrowed(flow, "/observability/runs", params)