A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Import shared MCP helpers in rlm.mcp instead of copying them (#2952)
Sebastian Müller4267eea1e7a2
diff --git a/prime-agent-runtime/src/rlm/mcp.py b/prime-agent-runtime/src/rlm/mcp.pyindex c82f503392..b08e42abe7 100644--- a/prime-agent-runtime/src/rlm/mcp.py+++ b/prime-agent-runtime/src/rlm/mcp.py@@ -18,18 +18,23 @@ import asyncioimport copyimport hashlibimport io-import jsonimport osimport reimport threadingimport timefrom contextlib import AsyncExitStackfrom collections.abc import Awaitable, Callable-from pathlib import Pathfrom typing import Any, TypeVarfrom . import host_request-from .mcp_base import McpToolError+from .mcp_base import (+ _EXPIRY_SKEW_SECONDS,+ McpToolError,+ _parse_result,+ _read_auth,+ _resolve_config_value,+ _resolve_streamable_http,+)__all__ = ["McpCredentialsUnavailable",@@ -894,7 +899,7 @@ async def _auth_identity(server: str, config: dict[str, Any]) -> str:provider = f"mcp:{server}"cred = _bound_auth(provider, config)expires = (cred or {}).get("expires")- if isinstance(expires, (int, float)) and expires <= time.time() * 1000 + 30_000:+ if isinstance(expires, (int, float)) and expires <= time.time() * 1000 + _EXPIRY_SKEW_SECONDS * 1000:try:await host_request("mcp.refresh", {"server": server})except Exception as exc:@@ -1037,87 +1042,3 @@ def _seconds(value: Any, default: float) -> float:def _strings(value: Any) -> bool:return isinstance(value, list) and all(isinstance(item, str) for item in value)---def _agent_dir() -> Path:- """Resolve the Prime Agent config dir the same way the rest of the runtime does."""- raw = (- os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")- or os.environ.get("PI_CODING_AGENT_DIR")- or str(Path.home() / ".prime" / "agent")- )- # resolve() so a relative env override reads auth.json from the right place,- # not relative to the kernel's cwd.- return Path(raw).expanduser().resolve()---def _read_auth(provider: str) -> dict[str, Any] | None:- """Read one credential entry from auth.json. Returns None if absent/unreadable."""- try:- data = json.loads((_agent_dir() / "auth.json").read_text())- except (OSError, ValueError):- return None- if not isinstance(data, dict):- return None- cred = data.get(provider)- return cred if isinstance(cred, dict) else None---def _resolve_config_value(value: str) -> str:- """Resolve a stored api_key value the way the host does.-- A value may be a literal, an env-var name, or a `!command` indirection. The- command form can't run safely in the kernel (the host injects those resolved),- so skip it; otherwise treat the value as an env-var name if set, else literal.- """- value = value.strip()- if not value or value.startswith("!"):- return ""- return (os.environ.get(value) or value).strip()---def _resolve_streamable_http():- """Return an SDK streamable-HTTP transport callable.-- SDK versions vary: some expose ``streamablehttp_client(url, headers=...)``,- others ``streamable_http_client(url, *, http_client=...)``, and some expose- both with *different* signatures.- """- from mcp.client import streamable_http as mod-- for name in ("streamablehttp_client", "streamable_http_client"):- fn = getattr(mod, name, None)- if fn is not None:- return fn- raise ImportError(- "the installed `mcp` SDK exposes no streamable-HTTP client; upgrade `mcp`"- )---def _parse_result(result: Any) -> Any:- """Normalize a CallToolResult into plain Python (structured output preferred).-- Raises McpToolError when the server flags the result as an error, so a failed- tool call doesn't look like a successful one to the caller.- """- texts: list[str] = []- for block in getattr(result, "content", None) or []:- text = getattr(block, "text", None)- if text is not None:- texts.append(text)- is_error = getattr(result, "is_error", getattr(result, "isError", False))- if is_error:- raise McpToolError("\n".join(texts) or "MCP tool returned an error")-- structured = getattr(result, "structured_content", getattr(result, "structuredContent", None))- if structured is not None: # falsy-but-valid payloads ({} / []) are real results- return structured- if texts:- return "\n".join(texts)-- # Non-text content (images, embedded resources): return them as plain dicts- # rather than the opaque SDK object so callers get usable data.- blocks = getattr(result, "content", None) or []- if blocks:- return [b.model_dump(mode="json") if hasattr(b, "model_dump") else b for b in blocks]- return result