Replace Codex MCP with native RMCP runtime

This commit is contained in:
Meta Vens 2026-07-21 19:27:28 +01:00
commit 2eb1410ad6
24 changed files with 4864 additions and 9297 deletions

View file

@ -104,9 +104,10 @@ The checkout has nine primary Epiphany Rust crates:
\code{epiphany-model-runtime}.
\item \code{epiphany-tool-adapter}: typed tool capability, invocation intent,
and invocation receipt documents.
\item \code{epiphany-tool-codex-mcp-spine}: quarantined Codex MCP adapter. It
consumes typed tool invocation intents and emits typed receipts; raw MCP JSON
remains adapter-edge cargo.
\item \code{epiphany-tool-mcp-runtime}: first-party tool executor. Native
Epiphany source tools are explicit local capabilities; foreign MCP calls use
the official RMCP SDK behind Epiphany-owned endpoint, process, network, and
receipt policy. Codex owns no tool discovery or execution path.
\end{itemize}
The vendored region contains:
@ -314,9 +315,10 @@ Proprioception refresh.
\subsection{Tool Calls}
Tool use travels through typed capability, invocation intent, and invocation
receipt documents. The Codex MCP adapter is an external compatibility executor.
MCP's raw JSON belongs at that boundary; Epiphany's internal tool state is the
typed intent/receipt pair.
receipt documents. The first-party tool runtime owns admission policy, native
tools, and typed receipts while the official RMCP SDK owns MCP lifecycle and
wire behavior. MCP's raw JSON belongs at that boundary; Epiphany's internal
tool state is the typed intent/receipt pair.
\subsection{Local Verse And Daemon Awareness}

View file

@ -56,7 +56,7 @@ const DETACHED_PROCESS: u32 = 0x0000_0008;
mod status_cli;
const DEFAULT_MODEL_RUNTIME_BIN: &str = "epiphany-model-runtime";
const DEFAULT_TOOL_ADAPTER_BIN: &str = "epiphany-tool-codex-mcp-spine";
const DEFAULT_TOOL_ADAPTER_BIN: &str = "epiphany-tool-mcp-runtime";
const WORKER_AUTO_TOOL_MAX_ROUNDS: usize = 24;
fn main() -> Result<()> {
@ -75,6 +75,7 @@ struct Args {
objective: Option<String>,
cwd: PathBuf,
codex_home: PathBuf,
mcp_config: PathBuf,
artifact_dir: PathBuf,
agent_memory_dir: PathBuf,
runtime_store: PathBuf,
@ -111,6 +112,7 @@ impl Args {
codex_home: env::var_os("CODEX_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".codex")),
mcp_config: root.join(".epiphany").join("mcp.toml"),
artifact_dir: root.join(".epiphany-dogfood").join("coordinator"),
agent_memory_dir: root.join("state").join("agents.msgpack"),
runtime_store: root.join("state").join("runtime-spine.msgpack"),
@ -137,9 +139,6 @@ impl Args {
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => {
let _ = take_path(&mut args, "--app-server")?;
}
"--model-runtime-bin" => {
parsed.model_runtime_bin = take_path(&mut args, "--model-runtime-bin")?;
}
@ -194,6 +193,7 @@ impl Args {
"--runtime-id" => parsed.runtime_id = Some(take_string(&mut args, "--runtime-id")?),
"--cwd" => parsed.cwd = take_path(&mut args, "--cwd")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--mcp-config" => parsed.mcp_config = take_path(&mut args, "--mcp-config")?,
"--artifact-dir" => parsed.artifact_dir = take_path(&mut args, "--artifact-dir")?,
"--agent-memory-dir" => {
parsed.agent_memory_dir = take_path(&mut args, "--agent-memory-dir")?;
@ -275,6 +275,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
let model_runtime_bin = resolve_model_runtime_bin(&root, &args.model_runtime_bin)?;
let tool_adapter_bin = resolve_model_runtime_bin(&root, &args.tool_adapter_bin)?;
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let mcp_config = status_cli::absolute_path(&args.mcp_config)?;
let artifact_dir = status_cli::absolute_path(&args.artifact_dir)?;
let agent_memory_dir = status_cli::absolute_path(&args.agent_memory_dir)?;
let runtime_store = status_cli::absolute_path(&args.runtime_store)?;
@ -398,6 +399,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
&args.model_provider,
&runtime_store,
&codex_home,
&mcp_config,
&cwd,
&worker_job_id,
"imagination",
@ -456,6 +458,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
&args.model_provider,
&runtime_store,
&codex_home,
&mcp_config,
&cwd,
&worker_job_id,
"imagination",
@ -693,6 +696,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
&args.model_provider,
&runtime_store,
&codex_home,
&mcp_config,
&cwd,
&worker_job_id,
role_id,
@ -752,6 +756,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
&args.model_provider,
&runtime_store,
&codex_home,
&mcp_config,
&cwd,
&worker_job_id,
"reorient-worker",
@ -849,6 +854,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
"toolAdapterBin".to_string(),
tool_adapter_bin.display().to_string(),
),
("mcpConfig".to_string(), mcp_config.display().to_string()),
("autoTools".to_string(), args.auto_tools.to_string()),
]),
resident_grant_id: args.resident_binding.get("grant-id").cloned(),
@ -872,6 +878,7 @@ fn run_coordinator(args: &Args) -> Result<Value> {
"autoTools": args.auto_tools,
"modelProvider": args.model_provider,
"codexHome": codex_home,
"mcpConfig": mcp_config,
"runtimeStore": runtime_store,
"runtimeSpine": runtime_status,
"workspace": cwd,
@ -1524,6 +1531,7 @@ fn launch_worker_runtime_detached(
model_provider: &str,
runtime_store: &Path,
codex_home: &Path,
mcp_config: &Path,
cwd: &Path,
job_id: &str,
role_id: &str,
@ -1549,6 +1557,8 @@ fn launch_worker_runtime_detached(
.arg(runtime_store)
.arg("--codex-home")
.arg(codex_home)
.arg("--mcp-config")
.arg(mcp_config)
.arg("--job-id")
.arg(job_id)
.arg("--max-runtime-seconds")

View file

@ -387,6 +387,7 @@ impl Args {
agent_memory_store: path("--agent-memory-store")?,
artifact_root: path("--artifact-root")?,
codex_home: path("--codex-home")?,
mcp_config: path("--mcp-config")?,
model_provider: value
.get("--model-provider")
.cloned()

View file

@ -8872,7 +8872,7 @@ mod tests {
"invocations": [
{
"intentId": "tool-intent-test",
"adapter": "codex-mcp",
"adapter": "epiphany-tools",
"server": "epiphany_source",
"toolName": "read_file",
"callId": "call-test",

View file

@ -1,5 +1,5 @@
use crate::open_epiphany_cultmesh_node;
use anyhow::{anyhow, bail, Context, Result};
use anyhow::{Context, Result, anyhow, bail};
use chrono::{DateTime, Utc};
use cultcache_rs::{DatabaseEntry, SingleFileMessagePackBackingStore};
use sha2::{Digest, Sha256};
@ -105,10 +105,7 @@ pub fn required_packaged_release_binaries(target_triple: &str) -> Vec<(&'static
),
("coordinator", file_name("epiphany-mvp-coordinator")),
("model-runtime", file_name("epiphany-model-runtime")),
(
"tool-codex-mcp-spine",
file_name("epiphany-tool-codex-mcp-spine"),
),
("tool-mcp-runtime", file_name("epiphany-tool-mcp-runtime")),
]
}
@ -410,10 +407,7 @@ fn required_release_build_target(role: &str) -> Result<(&'static str, &'static s
"persona-feedback-ingress" => Ok(("epiphany-core", "epiphany-persona-feedback-ingress")),
"coordinator" => Ok(("epiphany-core", "epiphany-mvp-coordinator")),
"model-runtime" => Ok(("epiphany-openai-runtime", "epiphany-model-runtime")),
"tool-codex-mcp-spine" => Ok((
"epiphany-tool-codex-mcp-spine",
"epiphany-tool-codex-mcp-spine",
)),
"tool-mcp-runtime" => Ok(("epiphany-tool-mcp-runtime", "epiphany-tool-mcp-runtime")),
_ => bail!("unknown required release role {role}"),
}
}
@ -850,7 +844,7 @@ mod tests {
let root = Path::new("isolated-release-build");
let core = release_manifest_target_dir(root, "epiphany-core");
let model = release_manifest_target_dir(root, "epiphany-openai-runtime");
let tools = release_manifest_target_dir(root, "epiphany-tool-codex-mcp-spine");
let tools = release_manifest_target_dir(root, "epiphany-tool-mcp-runtime");
assert_ne!(core, model);
assert_ne!(core, tools);
assert_ne!(model, tools);
@ -867,7 +861,7 @@ mod tests {
for manifest_dir in [
"epiphany-core",
"epiphany-openai-runtime",
"epiphany-tool-codex-mcp-spine",
"epiphany-tool-mcp-runtime",
] {
verify_owned_release_lock(repo, manifest_dir, &cargo)
.unwrap_or_else(|error| panic!("{manifest_dir} lockfile is not frozen: {error:#}"));
@ -886,7 +880,7 @@ mod tests {
"heartbeat",
"coordinator",
"model-runtime",
"tool-codex-mcp-spine",
"tool-mcp-runtime",
] {
assert!(packaged_roles.contains(role), "release omits {role}");
}
@ -911,11 +905,8 @@ mod tests {
("epiphany-openai-runtime", "epiphany-model-runtime")
);
assert_eq!(
required_release_build_target("tool-codex-mcp-spine").unwrap(),
(
"epiphany-tool-codex-mcp-spine",
"epiphany-tool-codex-mcp-spine"
)
required_release_build_target("tool-mcp-runtime").unwrap(),
("epiphany-tool-mcp-runtime", "epiphany-tool-mcp-runtime")
);
}
@ -964,13 +955,15 @@ mod tests {
fn witness_reader_refuses_tamper_and_inspector_refuses_wrong_runtime() {
let (d, e) = fixture();
let witness = Path::new(&e.package_root).join(EPIPHANY_PACKAGED_RELEASE_WITNESS_FILE);
assert!(inspect_epiphany_packaged_release_witness(
&witness,
d.path(),
"alien-runtime",
&e.source_commit_sha,
)
.is_err());
assert!(
inspect_epiphany_packaged_release_witness(
&witness,
d.path(),
"alien-runtime",
&e.source_commit_sha,
)
.is_err()
);
fs::write(&witness, b"hostile witness").unwrap();
assert!(read_epiphany_packaged_release_witness(&witness).is_err());
}

View file

@ -176,6 +176,7 @@ pub struct ResidentSelfPolicy {
pub agent_memory_store: PathBuf,
pub artifact_root: PathBuf,
pub codex_home: PathBuf,
pub mcp_config: PathBuf,
pub model_provider: String,
pub max_steps: u64,
pub turn_timeout_seconds: u64,
@ -202,6 +203,7 @@ impl ResidentSelfPolicy {
("agent memory store", &self.agent_memory_store),
("artifact root", &self.artifact_root),
("Codex home", &self.codex_home),
("MCP config", &self.mcp_config),
("release store", &self.release_store),
] {
if !path.is_absolute() {
@ -247,7 +249,7 @@ pub fn authenticate_resident_self_policy(policy: &mut ResidentSelfPolicy) -> Res
policy.model_runtime_bin =
crate::epiphany_packaged_release_binary_path(&witness, "model-runtime")?;
policy.tool_adapter_bin =
crate::epiphany_packaged_release_binary_path(&witness, "tool-codex-mcp-spine")?;
crate::epiphany_packaged_release_binary_path(&witness, "tool-mcp-runtime")?;
policy.release_commit = witness.source_commit_sha;
policy.release_manifest_digest = policy.release_witness_sha256.clone();
policy.validate()
@ -508,6 +510,8 @@ pub fn coordinator_argv(
policy.workspace.display().to_string(),
"--codex-home".into(),
policy.codex_home.display().to_string(),
"--mcp-config".into(),
policy.mcp_config.display().to_string(),
"--artifact-dir".into(),
artifact_dir.display().to_string(),
"--agent-memory-dir".into(),
@ -1580,12 +1584,13 @@ mod tests {
workspace: absolute("workspace"),
coordinator_bin: absolute("opt/epiphany/bin/epiphany-mvp-coordinator"),
model_runtime_bin: absolute("opt/epiphany/bin/epiphany-model-runtime"),
tool_adapter_bin: absolute("opt/epiphany/bin/epiphany-tool-codex-mcp-spine"),
tool_adapter_bin: absolute("opt/epiphany/bin/epiphany-tool-mcp-runtime"),
runtime_store: absolute("state/runtime.cc"),
local_verse_store: absolute("state/verse.cc"),
agent_memory_store: absolute("state/mind.cc"),
artifact_root: absolute("state/artifacts"),
codex_home: absolute("state/codex"),
mcp_config: absolute("state/epiphany-mcp.toml"),
model_provider: "local".into(),
max_steps: 2,
turn_timeout_seconds: 60,

View file

@ -12070,7 +12070,7 @@ pub(crate) mod tests {
"intent:done",
&EpiphanyToolInvocationIntent::new(
"done",
"codex-mcp",
"epiphany-tools",
"smoke-server",
"smoke_tool",
"{}",
@ -12083,7 +12083,7 @@ pub(crate) mod tests {
"intent:pending",
&EpiphanyToolInvocationIntent::new(
"pending",
"codex-mcp",
"epiphany-tools",
"smoke-server",
"waiting_tool",
"{}",
@ -12095,7 +12095,7 @@ pub(crate) mod tests {
let mut failed_receipt = EpiphanyToolInvocationReceipt::new(
"receipt-done",
"done",
"codex-mcp",
"epiphany-tools",
"smoke-server",
"smoke_tool",
"failed",

View file

@ -369,6 +369,7 @@ struct RunWorkerCliOptions {
provider: String,
store_path: PathBuf,
codex_home: PathBuf,
mcp_config: Option<PathBuf>,
job_id: String,
model: String,
auto_tools: bool,
@ -468,6 +469,7 @@ fn parse_run_worker_options(args: Vec<String>) -> Result<RunWorkerCliOptions> {
let mut provider = DEFAULT_PROVIDER.to_string();
let mut store_path = PathBuf::from(DEFAULT_STORE);
let mut codex_home = default_codex_home()?;
let mut mcp_config = None;
let mut job_id = None;
let mut model = default_worker_model();
let mut auto_tools = false;
@ -481,6 +483,9 @@ fn parse_run_worker_options(args: Vec<String>) -> Result<RunWorkerCliOptions> {
"--provider" => provider = next_value(&mut iter, "--provider")?,
"--store" => store_path = PathBuf::from(next_value(&mut iter, "--store")?),
"--codex-home" => codex_home = PathBuf::from(next_value(&mut iter, "--codex-home")?),
"--mcp-config" => {
mcp_config = Some(PathBuf::from(next_value(&mut iter, "--mcp-config")?))
}
"--job-id" => job_id = Some(next_value(&mut iter, "--job-id")?),
"--model" | "--default-model" => model = next_value(&mut iter, "--model")?,
"--auto-tools" => auto_tools = true,
@ -501,6 +506,7 @@ fn parse_run_worker_options(args: Vec<String>) -> Result<RunWorkerCliOptions> {
provider,
store_path,
codex_home,
mcp_config,
job_id: job_id.context("run-worker requires --job-id")?,
model,
auto_tools,
@ -682,7 +688,7 @@ async fn run_worker_launch_with_tool_continuation(
adapter_runs.push(run_tool_adapter(
&tool_adapter_bin,
&options.store_path,
&options.codex_home,
options.mcp_config.as_ref(),
options.cwd.as_ref(),
&intent_id,
)?);
@ -1224,7 +1230,7 @@ mod tests {
fn tool_intent_fingerprint_ignores_argument_key_order() {
let left = EpiphanyToolInvocationIntent::new(
"left",
"codex-mcp",
"epiphany-tools",
"epiphany_source",
"read_file",
r#"{"path":"README.md","offset":0}"#,
@ -1234,7 +1240,7 @@ mod tests {
);
let right = EpiphanyToolInvocationIntent::new(
"right",
"codex-mcp",
"epiphany-tools",
"epiphany_source",
"read_file",
r#"{"offset":0,"path":"README.md"}"#,
@ -1270,7 +1276,7 @@ async fn run_worker_options(options: RunWorkerCliOptions) -> Result<serde_json::
fn run_tool_adapter(
tool_adapter_bin: &PathBuf,
store_path: &PathBuf,
codex_home: &PathBuf,
mcp_config: Option<&PathBuf>,
cwd: Option<&PathBuf>,
intent_id: &str,
) -> Result<serde_json::Value> {
@ -1280,9 +1286,10 @@ fn run_tool_adapter(
.arg("--store")
.arg(store_path)
.arg("--intent-id")
.arg(intent_id)
.arg("--codex-home")
.arg(codex_home);
.arg(intent_id);
if let Some(mcp_config) = mcp_config {
command.arg("--mcp-config").arg(mcp_config);
}
if let Some(cwd) = cwd {
command.arg("--cwd").arg(cwd);
}
@ -1395,5 +1402,5 @@ fn now() -> String {
}
fn usage() -> &'static str {
"usage: epiphany-model-runtime <model-turn|run-worker|tool-followup|tool-followup-turn|smoke> [--provider openai-codex] [--store path] [--codex-home path] [--request path] [--request-id id] [--followup-request-id id] [--output path] [--session-id id] [--job-id id] [--objective text] [--default-model model] [--output-last-message path] [--auto-tools --tool-adapter-bin path --cwd path --max-tool-rounds n]"
"usage: epiphany-model-runtime <model-turn|run-worker|tool-followup|tool-followup-turn|smoke> [--provider openai-codex] [--store path] [--codex-home path] [--request path] [--request-id id] [--followup-request-id id] [--output path] [--session-id id] [--job-id id] [--objective text] [--default-model model] [--output-last-message path] [--auto-tools --tool-adapter-bin path --mcp-config path --cwd path --max-tool-rounds n]"
}

View file

@ -40,7 +40,7 @@ use epiphany_openai_codex_spine::EpiphanyResponsesFrameObservation;
use epiphany_openai_codex_spine::auth_manager;
pub use epiphany_openai_codex_spine::default_codex_home;
use epiphany_openai_codex_spine::status_from_auth_manager;
use epiphany_tool_adapter::CODEX_MCP_TOOL_ADAPTER_ID;
use epiphany_tool_adapter::EPIPHANY_TOOL_RUNTIME_ADAPTER_ID;
use epiphany_tool_adapter::EpiphanyToolInvocationIntent;
use epiphany_tool_adapter::EpiphanyToolInvocationReceipt;
use epiphany_tool_adapter::tool_invocation_intent_key;
@ -1250,7 +1250,7 @@ pub fn tool_invocation_intent_from_model_event(
event.sequence,
sanitize_request_id(call_id)
),
CODEX_MCP_TOOL_ADAPTER_ID,
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID,
server,
tool_name,
arguments.clone(),
@ -2552,7 +2552,7 @@ mod tests {
.expect("MCP-shaped tool call should produce an intent");
assert_eq!(
intent.adapter,
epiphany_tool_adapter::CODEX_MCP_TOOL_ADAPTER_ID
epiphany_tool_adapter::EPIPHANY_TOOL_RUNTIME_ADAPTER_ID
);
assert_eq!(intent.server, "calendar_server");
assert_eq!(intent.tool_name, "list_events");
@ -2629,7 +2629,7 @@ mod tests {
let mut tool_receipt = EpiphanyToolInvocationReceipt::new(
"receipt-tool",
intent_id.clone(),
epiphany_tool_adapter::CODEX_MCP_TOOL_ADAPTER_ID,
epiphany_tool_adapter::EPIPHANY_TOOL_RUNTIME_ADAPTER_ID,
"smoke_server",
"smoke_tool",
"completed",

View file

@ -3,7 +3,7 @@ use cultcache_rs::DatabaseEntry;
pub const TOOL_ADAPTER_CAPABILITY_SCHEMA_ID: &str = "epiphany.tool_capability.v0";
pub const TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID: &str = "epiphany.tool_invocation_intent.v0";
pub const TOOL_ADAPTER_INVOCATION_RECEIPT_SCHEMA_ID: &str = "epiphany.tool_invocation_receipt.v0";
pub const CODEX_MCP_TOOL_ADAPTER_ID: &str = "codex-mcp";
pub const EPIPHANY_TOOL_RUNTIME_ADAPTER_ID: &str = "epiphany-tools";
pub fn tool_invocation_intent_key(intent_id: &str) -> String {
format!("intent:{intent_id}")

File diff suppressed because it is too large Load diff

View file

@ -1,33 +0,0 @@
[package]
name = "epiphany-tool-codex-mcp-spine"
version = "0.1.0"
edition = "2024"
publish = false
license-file = "../LICENSE"
[dependencies]
anyhow = "1"
allocative = { version = "=0.3.4", features = ["hashbrown"] }
async-channel = "2"
codex-config = { path = "../vendor/codex/codex-rs/config" }
codex-exec-server = { path = "../vendor/codex/codex-rs/exec-server" }
codex-mcp = { path = "../vendor/codex/codex-rs/codex-mcp" }
codex-protocol = { path = "../vendor/codex/codex-rs/protocol" }
cultcache-rs = { path = "../vendor/cultcache-rs" }
epiphany-core = { path = "../epiphany-core" }
epiphany-tool-adapter = { path = "../epiphany-tool-adapter" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
toml = "0.9"
[[bin]]
name = "epiphany-tool-codex-mcp-spine"
path = "src/main.rs"
[patch.crates-io]
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "132f5b39c862e3a970f731d709608b3e6276d5f6" }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }

View file

@ -1,735 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use async_channel::unbounded;
use codex_config::CONFIG_TOML_FILE;
use codex_config::Constrained;
use codex_config::config_toml::ConfigToml;
use codex_config::load_global_mcp_servers;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
use codex_mcp::McpConfig;
use codex_mcp::McpConnectionManager;
use codex_mcp::McpRuntimeEnvironment;
use codex_mcp::compute_auth_statuses;
use codex_mcp::effective_mcp_servers;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
use epiphany_tool_adapter::CODEX_MCP_TOOL_ADAPTER_ID;
use epiphany_tool_adapter::EpiphanyToolInvocationIntent;
use epiphany_tool_adapter::EpiphanyToolInvocationReceipt;
use epiphany_tool_adapter::tool_invocation_intent_key;
use epiphany_tool_adapter::tool_invocation_receipt_key;
use serde::Serialize;
use serde_json::Value;
use serde_json::json;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
const ADAPTER_ID: &str = CODEX_MCP_TOOL_ADAPTER_ID;
#[tokio::main]
async fn main() -> Result<()> {
let command = Command::parse(std::env::args().skip(1).collect())?;
match command {
Command::Run(options) => {
let summary = run_invocation(options).await?;
println!("{}", serde_json::to_string_pretty(&summary)?);
}
Command::Smoke(options) => {
let summary = smoke(options)?;
println!("{}", serde_json::to_string_pretty(&summary)?);
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Command {
Run(RunOptions),
Smoke(SmokeOptions),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct RunOptions {
store: PathBuf,
intent_id: String,
codex_home: Option<PathBuf>,
cwd: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SmokeOptions {
store: PathBuf,
intent_id: String,
}
impl Command {
fn parse(args: Vec<String>) -> Result<Self> {
let (command, rest) = args
.split_first()
.ok_or_else(|| anyhow!("usage: epiphany-tool-codex-mcp-spine <run|smoke> ..."))?;
let values = parse_flags(rest)?;
match command.as_str() {
"run" => Ok(Self::Run(RunOptions {
store: required_path(&values, "store")?,
intent_id: required_string(&values, "intent-id")?,
codex_home: optional_path(&values, "codex-home")?,
cwd: optional_path(&values, "cwd")?,
})),
"smoke" => Ok(Self::Smoke(SmokeOptions {
store: required_path(&values, "store")?,
intent_id: values
.get("intent-id")
.cloned()
.unwrap_or_else(|| "codex-mcp-spine-smoke".to_string()),
})),
other => Err(anyhow!("unknown command {other:?}; expected run or smoke")),
}
}
}
fn parse_flags(args: &[String]) -> Result<BTreeMap<String, String>> {
let mut values = BTreeMap::new();
let mut iter = args.iter();
while let Some(flag) = iter.next() {
let name = flag
.strip_prefix("--")
.ok_or_else(|| anyhow!("expected --flag, got {flag:?}"))?;
let value = iter
.next()
.ok_or_else(|| anyhow!("missing value for --{name}"))?;
values.insert(name.to_string(), value.to_string());
}
Ok(values)
}
fn required_string(values: &BTreeMap<String, String>, name: &str) -> Result<String> {
values
.get(name)
.cloned()
.ok_or_else(|| anyhow!("missing --{name}"))
}
fn required_path(values: &BTreeMap<String, String>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(required_string(values, name)?))
}
fn optional_path(values: &BTreeMap<String, String>, name: &str) -> Result<Option<PathBuf>> {
Ok(values.get(name).map(PathBuf::from))
}
fn open_store(path: &Path) -> Result<cultcache_rs::CultCache> {
let mut cache = epiphany_core::runtime_spine_cache(path)?;
cache.pull_all_backing_stores()?;
Ok(cache)
}
async fn run_invocation(options: RunOptions) -> Result<RunSummary> {
let mut cache = open_store(&options.store)?;
let intent = cache
.get_required::<EpiphanyToolInvocationIntent>(&tool_invocation_intent_key(
&options.intent_id,
))
.with_context(|| {
format!(
"failed to load tool invocation intent {}",
options.intent_id
)
})?;
validate_intent(&intent)?;
let completed_at = now_utc_string();
let receipt_id = receipt_id(&intent.intent_id);
let result = execute_codex_mcp(&intent, &options).await;
let mut receipt = EpiphanyToolInvocationReceipt::new(
receipt_id.clone(),
intent.intent_id.clone(),
intent.adapter.clone(),
intent.server.clone(),
intent.tool_name.clone(),
if result.is_ok() {
"completed"
} else {
"failed"
},
completed_at,
);
match result {
Ok(result) => {
receipt.result_json = Some(serde_json::to_string(&result)?);
}
Err(error) => {
receipt.error = Some(format!("{error:#}"));
}
}
cache.put(tool_invocation_receipt_key(&receipt.intent_id), &receipt)?;
Ok(RunSummary {
adapter: ADAPTER_ID.to_string(),
store: options.store.display().to_string(),
intent_id: intent.intent_id,
receipt_id,
status: receipt.status,
schemas: schema_map(),
})
}
async fn execute_codex_mcp(
intent: &EpiphanyToolInvocationIntent,
options: &RunOptions,
) -> Result<Value> {
let cwd = options
.cwd
.clone()
.unwrap_or(std::env::current_dir().context("failed to resolve current directory")?);
if intent.server == "epiphany_source" {
return execute_builtin_epiphany_source(intent, options, &cwd);
}
let codex_home = resolve_codex_home(options.codex_home.clone())?;
let mcp_config = load_mcp_config(&codex_home).await?;
let mut mcp_servers = effective_mcp_servers(&mcp_config, None);
mcp_servers.retain(|name, _| name == &intent.server);
if mcp_servers.is_empty() {
return Err(anyhow!(
"Codex MCP has no effective server named {:?}",
intent.server
));
}
let auth_statuses = compute_auth_statuses(
mcp_servers.iter(),
mcp_config.mcp_oauth_credentials_store_mode,
)
.await;
let (tx_event, rx_event) = unbounded();
drop(rx_event);
let runtime_environment =
McpRuntimeEnvironment::new(Arc::new(Environment::default_for_tests()), cwd);
let (manager, cancel_token) = McpConnectionManager::new(
&mcp_servers,
mcp_config.mcp_oauth_credentials_store_mode,
auth_statuses,
&mcp_config.approval_policy,
format!("epiphany-tool-{}", intent.intent_id),
tx_event,
SandboxPolicy::new_read_only_policy(),
runtime_environment,
)
.await;
let arguments = parse_arguments(&intent.arguments_json)?;
let result = manager
.call_tool(&intent.server, &intent.tool_name, arguments, None)
.await
.with_context(|| {
format!(
"Codex MCP call failed for server {:?} tool {:?}",
intent.server, intent.tool_name
)
});
cancel_token.cancel();
Ok(serde_json::to_value(result?)?)
}
fn execute_builtin_epiphany_source(
intent: &EpiphanyToolInvocationIntent,
options: &RunOptions,
cwd: &Path,
) -> Result<Value> {
let arguments = parse_arguments(&intent.arguments_json)?.unwrap_or(Value::Null);
match intent.tool_name.as_str() {
"read_file" => builtin_read_file(cwd, &arguments),
"git_show" => builtin_git_show(cwd, &arguments),
"read_hands_receipt" => builtin_read_hands_receipt(&options.store, &arguments),
other => Err(anyhow!("unknown built-in epiphany_source tool {:?}", other)),
}
}
fn builtin_read_file(cwd: &Path, arguments: &Value) -> Result<Value> {
let path = required_arg_string(arguments, "path")?;
let start_line = optional_arg_u64(arguments, "startLine")?
.unwrap_or(1)
.max(1) as usize;
let max_lines = optional_arg_u64(arguments, "maxLines")?
.unwrap_or(120)
.clamp(1, 240) as usize;
let path = resolve_read_path(cwd, path)?;
let text =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
let lines = text
.lines()
.enumerate()
.skip(start_line.saturating_sub(1))
.take(max_lines)
.map(|(index, line)| format!("{}: {}", index + 1, line))
.collect::<Vec<_>>();
Ok(json!({
"path": path.display().to_string(),
"startLine": start_line,
"maxLines": max_lines,
"lineCount": text.lines().count(),
"content": lines.join("\n")
}))
}
fn builtin_git_show(cwd: &Path, arguments: &Value) -> Result<Value> {
let revision = required_arg_string(arguments, "revision")?;
let max_bytes = optional_arg_u64(arguments, "maxBytes")?
.unwrap_or(16_000)
.clamp(512, 24_000) as usize;
let mut command = std::process::Command::new("git");
command
.current_dir(cwd)
.arg("show")
.arg("--stat")
.arg("--patch")
.arg("--format=medium")
.arg(revision)
.arg("--");
if let Some(paths) = arguments.get("paths").and_then(Value::as_array) {
for path in paths.iter().filter_map(Value::as_str) {
command.arg(path);
}
}
let output = command.output().context("failed to run git show")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
Ok(json!({
"revision": revision,
"status": output.status.code(),
"success": output.status.success(),
"stdout": truncate_chars(&stdout, max_bytes),
"stderr": truncate_chars(&stderr, 4000)
}))
}
fn builtin_read_hands_receipt(store: &Path, arguments: &Value) -> Result<Value> {
let receipt_id = required_arg_string(arguments, "receiptId")?;
let kind = required_arg_string(arguments, "kind")?;
match kind {
"patch" => {
let receipt = epiphany_core::runtime_hands_patch_receipt(store, receipt_id)?
.ok_or_else(|| anyhow!("Hands patch receipt {:?} not found", receipt_id))?;
Ok(json!({
"kind": "patch",
"schemaVersion": receipt.schema_version,
"receiptId": receipt.receipt_id,
"intentId": receipt.intent_id,
"reviewId": receipt.review_id,
"runtimeJobId": receipt.runtime_job_id,
"changedPaths": receipt.changed_paths,
"summary": receipt.summary,
"emittedAt": receipt.emitted_at,
"contract": receipt.contract
}))
}
"command" => {
let receipt = epiphany_core::runtime_hands_command_receipt(store, receipt_id)?
.ok_or_else(|| anyhow!("Hands command receipt {:?} not found", receipt_id))?;
Ok(json!({
"kind": "command",
"schemaVersion": receipt.schema_version,
"receiptId": receipt.receipt_id,
"intentId": receipt.intent_id,
"reviewId": receipt.review_id,
"runtimeJobId": receipt.runtime_job_id,
"command": receipt.command,
"exitCode": receipt.exit_code,
"stdoutArtifact": receipt.stdout_artifact,
"stderrArtifact": receipt.stderr_artifact,
"summary": receipt.summary,
"emittedAt": receipt.emitted_at,
"contract": receipt.contract
}))
}
"commit" => {
let receipt = epiphany_core::runtime_hands_commit_receipt(store, receipt_id)?
.ok_or_else(|| anyhow!("Hands commit receipt {:?} not found", receipt_id))?;
Ok(json!({
"kind": "commit",
"schemaVersion": receipt.schema_version,
"receiptId": receipt.receipt_id,
"intentId": receipt.intent_id,
"reviewId": receipt.review_id,
"runtimeJobId": receipt.runtime_job_id,
"commitSha": receipt.commit_sha,
"branch": receipt.branch,
"changedPaths": receipt.changed_paths,
"summary": receipt.summary,
"emittedAt": receipt.emitted_at,
"contract": receipt.contract
}))
}
other => Err(anyhow!("unsupported Hands receipt kind {:?}", other)),
}
}
fn resolve_read_path(cwd: &Path, path: &str) -> Result<PathBuf> {
let requested = PathBuf::from(path);
let candidate = if requested.is_absolute() {
requested
} else {
cwd.join(requested)
};
let cwd = cwd
.canonicalize()
.with_context(|| format!("failed to canonicalize cwd {}", cwd.display()))?;
let candidate = candidate
.canonicalize()
.with_context(|| format!("failed to canonicalize requested path {}", path))?;
if !candidate.starts_with(&cwd) {
return Err(anyhow!(
"read path {} escapes workspace {}",
candidate.display(),
cwd.display()
));
}
Ok(candidate)
}
fn required_arg_string<'a>(arguments: &'a Value, name: &str) -> Result<&'a str> {
arguments
.get(name)
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| anyhow!("missing required string argument {name:?}"))
}
fn optional_arg_u64(arguments: &Value, name: &str) -> Result<Option<u64>> {
match arguments.get(name) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_u64()
.map(Some)
.ok_or_else(|| anyhow!("argument {name:?} must be an unsigned integer")),
}
}
fn truncate_chars(text: &str, max_chars: usize) -> String {
if text.chars().count() <= max_chars {
return text.to_string();
}
let mut truncated = text.chars().take(max_chars).collect::<String>();
truncated.push_str("\n...<truncated>");
truncated
}
async fn load_mcp_config(codex_home: &Path) -> Result<McpConfig> {
let config_toml = read_codex_config_toml(codex_home)?;
let mcp_servers = load_global_mcp_servers(codex_home).await.with_context(|| {
format!(
"failed to load Codex MCP servers from {}",
codex_home.join(CONFIG_TOML_FILE).display()
)
})?;
Ok(McpConfig {
chatgpt_base_url: config_toml
.as_ref()
.and_then(|config| config.chatgpt_base_url.clone())
.unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()),
codex_home: codex_home.to_path_buf(),
mcp_oauth_credentials_store_mode: config_toml
.as_ref()
.and_then(|config| config.mcp_oauth_credentials_store)
.unwrap_or(OAuthCredentialsStoreMode::Auto),
mcp_oauth_callback_port: config_toml
.as_ref()
.and_then(|config| config.mcp_oauth_callback_port),
mcp_oauth_callback_url: config_toml
.as_ref()
.and_then(|config| config.mcp_oauth_callback_url.clone()),
approval_policy: Constrained::allow_any(
config_toml
.as_ref()
.and_then(|config| config.approval_policy)
.unwrap_or(AskForApproval::Never),
),
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
configured_mcp_servers: mcp_servers.into_iter().collect::<HashMap<_, _>>(),
})
}
fn read_codex_config_toml(codex_home: &Path) -> Result<Option<ConfigToml>> {
let path = codex_home.join(CONFIG_TOML_FILE);
if !path.exists() {
return Ok(None);
}
let raw = fs::read_to_string(&path)
.with_context(|| format!("failed to read Codex config {}", path.display()))?;
toml::from_str::<ConfigToml>(&raw)
.map(Some)
.with_context(|| format!("failed to parse Codex config {}", path.display()))
}
fn resolve_codex_home(explicit: Option<PathBuf>) -> Result<PathBuf> {
if let Some(path) = explicit {
return Ok(path);
}
if let Some(path) = std::env::var_os("CODEX_HOME") {
return Ok(PathBuf::from(path));
}
let user_profile = std::env::var_os("USERPROFILE")
.or_else(|| std::env::var_os("HOME"))
.ok_or_else(|| anyhow!("cannot resolve Codex home: set --codex-home or CODEX_HOME"))?;
Ok(PathBuf::from(user_profile).join(".codex"))
}
fn parse_arguments(arguments_json: &str) -> Result<Option<Value>> {
let trimmed = arguments_json.trim();
if trimmed.is_empty() || trimmed == "null" {
return Ok(None);
}
let value: Value = serde_json::from_str(trimmed).context("arguments_json is not valid JSON")?;
match value {
Value::Null => Ok(None),
Value::Object(_) => Ok(Some(value)),
other => Err(anyhow!(
"arguments_json must decode to a JSON object or null, got {}",
json_kind(&other)
)),
}
}
fn validate_intent(intent: &EpiphanyToolInvocationIntent) -> Result<()> {
if intent.schema_id != epiphany_tool_adapter::TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID {
return Err(anyhow!(
"intent {} has schema_id {:?}, expected {:?}",
intent.intent_id,
intent.schema_id,
epiphany_tool_adapter::TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID
));
}
if intent.adapter != ADAPTER_ID {
return Err(anyhow!(
"intent {} targets adapter {:?}, expected {:?}",
intent.intent_id,
intent.adapter,
ADAPTER_ID
));
}
if intent.server.trim().is_empty() {
return Err(anyhow!("intent {} has empty MCP server", intent.intent_id));
}
if intent.tool_name.trim().is_empty() {
return Err(anyhow!(
"intent {} has empty MCP tool name",
intent.intent_id
));
}
Ok(())
}
fn smoke(options: SmokeOptions) -> Result<SmokeSummary> {
let mut cache = open_store(&options.store)?;
let intent = EpiphanyToolInvocationIntent::new(
options.intent_id.clone(),
ADAPTER_ID,
"smoke-server",
"smoke-tool",
"{}",
"epiphany-tool-codex-mcp-spine smoke",
"prove typed Codex MCP quarantine store round-trip",
now_utc_string(),
);
let receipt = EpiphanyToolInvocationReceipt::new(
receipt_id(&intent.intent_id),
intent.intent_id.clone(),
ADAPTER_ID,
intent.server.clone(),
intent.tool_name.clone(),
"smoke",
now_utc_string(),
);
cache.put(tool_invocation_intent_key(&intent.intent_id), &intent)?;
cache.put(tool_invocation_receipt_key(&intent.intent_id), &receipt)?;
Ok(SmokeSummary {
adapter: ADAPTER_ID.to_string(),
store: options.store.display().to_string(),
intent_id: intent.intent_id,
receipt_id: receipt.receipt_id,
schemas: schema_map(),
})
}
fn receipt_id(intent_id: &str) -> String {
format!("receipt-{intent_id}-{}", unix_millis())
}
fn now_utc_string() -> String {
format!("unix-ms:{}", unix_millis())
}
fn unix_millis() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
}
fn json_kind(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn schema_map() -> BTreeMap<String, String> {
BTreeMap::from([
(
"capability".to_string(),
epiphany_tool_adapter::TOOL_ADAPTER_CAPABILITY_SCHEMA_ID.to_string(),
),
(
"intent".to_string(),
epiphany_tool_adapter::TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID.to_string(),
),
(
"receipt".to_string(),
epiphany_tool_adapter::TOOL_ADAPTER_INVOCATION_RECEIPT_SCHEMA_ID.to_string(),
),
])
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct RunSummary {
adapter: String,
store: String,
intent_id: String,
receipt_id: String,
status: String,
schemas: BTreeMap<String, String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct SmokeSummary {
adapter: String,
store: String,
intent_id: String,
receipt_id: String,
schemas: BTreeMap<String, String>,
}
#[cfg(test)]
mod tests {
use super::*;
fn unique_temp_dir(label: &str) -> Result<PathBuf> {
let path = std::env::temp_dir().join(format!("{label}-{}", unix_millis()));
fs::create_dir_all(&path)?;
Ok(path)
}
#[test]
fn parses_object_or_null_arguments_only() -> Result<()> {
assert_eq!(parse_arguments("")?, None);
assert_eq!(parse_arguments("null")?, None);
assert!(parse_arguments(r#"{"path":"state/map.yaml"}"#)?.is_some());
assert!(parse_arguments("[]").is_err());
Ok(())
}
#[test]
fn rejects_non_codex_mcp_adapter() {
let intent = EpiphanyToolInvocationIntent::new(
"i",
"heimdall-eventually",
"server",
"tool",
"{}",
"test",
"test",
"now",
);
assert!(validate_intent(&intent).is_err());
}
#[test]
fn builtin_epiphany_source_reads_bounded_file_slice() -> Result<()> {
let temp = unique_temp_dir("epiphany-source-read-file")?;
let source = temp.join("src.txt");
fs::write(&source, "one\ntwo\nthree\nfour\n")?;
let result = builtin_read_file(
&temp,
&json!({"path": "src.txt", "startLine": 2, "maxLines": 2}),
)?;
assert_eq!(result["startLine"], 2);
assert!(result["content"].as_str().unwrap().contains("2: two"));
assert!(result["content"].as_str().unwrap().contains("3: three"));
assert!(!result["content"].as_str().unwrap().contains("4: four"));
fs::remove_dir_all(&temp)?;
Ok(())
}
#[test]
fn builtin_epiphany_source_reads_hands_receipt_body() -> Result<()> {
let temp = unique_temp_dir("epiphany-source-read-receipt")?;
let store = temp.join("runtime-spine.msgpack");
epiphany_core::initialize_runtime_spine(
&store,
epiphany_core::RuntimeSpineInitOptions {
runtime_id: "epiphany-source-test".to_string(),
display_name: "Epiphany Source Test".to_string(),
created_at: "2026-06-12T00:00:00Z".to_string(),
},
)?;
let intent = epiphany_core::HandsActionIntent {
schema_version: epiphany_core::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(),
intent_id: "hands-intent-test".to_string(),
runtime_job_id: "hands-job-test".to_string(),
binding_id: "implementation-worker".to_string(),
role: "epiphany-hands".to_string(),
authority_scope: "epiphany.role.implementation".to_string(),
requested_action: "continueImplementation".to_string(),
requested_paths: vec![".".to_string()],
substrate_gate_grant_receipt_id: "substrate-grant-test".to_string(),
requested_at: "2026-06-12T00:00:00Z".to_string(),
contract: "test intent".to_string(),
};
epiphany_core::put_hands_action_intent(&store, &intent)?;
let review = epiphany_core::hands_action_review_for_intent(
"hands-review-test".to_string(),
&intent,
"approved".to_string(),
vec!["patch".to_string()],
vec!["test".to_string()],
"2026-06-12T00:00:01Z".to_string(),
);
epiphany_core::put_hands_action_review(&store, &review)?;
let patch = epiphany_core::hands_patch_receipt_for_review(
"hands-patch-test".to_string(),
&intent,
&review,
vec!["epiphany-core/src/lib.rs".to_string()],
"patch summary".to_string(),
"2026-06-12T00:00:02Z".to_string(),
);
epiphany_core::put_hands_patch_receipt(&store, &patch)?;
let result = builtin_read_hands_receipt(
&store,
&json!({"kind": "patch", "receiptId": "hands-patch-test"}),
)?;
assert_eq!(result["kind"], "patch");
assert_eq!(result["receiptId"], "hands-patch-test");
assert_eq!(result["changedPaths"][0], "epiphany-core/src/lib.rs");
fs::remove_dir_all(&temp)?;
Ok(())
}
}

1
epiphany-tool-mcp-runtime/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target/

3587
epiphany-tool-mcp-runtime/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,26 @@
[package]
name = "epiphany-tool-mcp-runtime"
version = "0.1.0"
edition = "2024"
publish = false
license-file = "../LICENSE"
[dependencies]
anyhow = "1"
epiphany-tool-adapter = { path = "../epiphany-tool-adapter" }
epiphany-core = { path = "../epiphany-core" }
cultcache-rs = { path = "../vendor/cultcache-rs" }
http = "1"
reqwest = { version = "0.13.2", default-features = false, features = ["json", "rustls"] }
rmcp = { version = "2.2.0", default-features = false, features = ["client", "transport-child-process", "transport-streamable-http-client-reqwest"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["io-util", "macros", "process", "rt-multi-thread", "time"] }
toml = "0.9"
[dev-dependencies]
tempfile = "3"
[[bin]]
name = "epiphany-tool-mcp-runtime"
path = "src/main.rs"

View file

@ -0,0 +1,252 @@
use anyhow::{Context, Result, anyhow};
use serde::{Deserialize, Deserializer};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::time::Duration;
fn default_enabled() -> bool {
true
}
fn default_startup_timeout() -> u64 {
10
}
fn default_tool_timeout() -> u64 {
60
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct McpRuntimeConfig {
#[serde(default)]
pub mcp_servers: BTreeMap<String, McpServerConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpServerConfig {
pub transport: McpTransportConfig,
pub enabled: bool,
pub startup_timeout_sec: u64,
pub tool_timeout_sec: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpTransportConfig {
Stdio {
command: String,
args: Vec<String>,
env: HashMap<String, String>,
cwd: Option<PathBuf>,
},
Http {
url: String,
bearer_token_env_var: Option<String>,
http_headers: HashMap<String, String>,
env_http_headers: HashMap<String, String>,
},
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawMcpServerConfig {
command: Option<String>,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: HashMap<String, String>,
cwd: Option<PathBuf>,
url: Option<String>,
bearer_token_env_var: Option<String>,
#[serde(default)]
http_headers: HashMap<String, String>,
#[serde(default)]
env_http_headers: HashMap<String, String>,
#[serde(default = "default_enabled")]
enabled: bool,
#[serde(default = "default_startup_timeout")]
startup_timeout_sec: u64,
#[serde(default = "default_tool_timeout")]
tool_timeout_sec: u64,
}
impl<'de> Deserialize<'de> for McpServerConfig {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let raw = RawMcpServerConfig::deserialize(deserializer)?;
let transport = match (raw.command, raw.url) {
(Some(command), None)
if raw.bearer_token_env_var.is_none()
&& raw.http_headers.is_empty()
&& raw.env_http_headers.is_empty() =>
{
McpTransportConfig::Stdio {
command,
args: raw.args,
env: raw.env,
cwd: raw.cwd,
}
}
(None, Some(url)) if raw.args.is_empty() && raw.env.is_empty() && raw.cwd.is_none() => {
McpTransportConfig::Http {
url,
bearer_token_env_var: raw.bearer_token_env_var,
http_headers: raw.http_headers,
env_http_headers: raw.env_http_headers,
}
}
_ => {
return Err(serde::de::Error::custom(
"MCP server must configure exactly one coherent stdio or HTTP transport",
));
}
};
Ok(Self {
transport,
enabled: raw.enabled,
startup_timeout_sec: raw.startup_timeout_sec,
tool_timeout_sec: raw.tool_timeout_sec,
})
}
}
impl McpRuntimeConfig {
pub fn from_path(path: &Path) -> Result<Self> {
let raw = std::fs::read_to_string(path)
.with_context(|| format!("reading MCP config {}", path.display()))?;
Self::from_toml(&raw)
}
pub fn from_toml(raw: &str) -> Result<Self> {
let config: Self = toml::from_str(raw).context("decoding MCP config")?;
config.validate()?;
Ok(config)
}
pub fn server(&self, name: &str) -> Result<&McpServerConfig> {
let server = self
.mcp_servers
.get(name)
.ok_or_else(|| anyhow!("MCP server {name:?} is not configured"))?;
if !server.enabled {
return Err(anyhow!("MCP server {name:?} is disabled"));
}
Ok(server)
}
fn validate(&self) -> Result<()> {
for (name, server) in &self.mcp_servers {
if name.trim().is_empty()
|| server.startup_timeout_sec == 0
|| server.tool_timeout_sec == 0
{
return Err(anyhow!("MCP server name and timeouts must be nonzero"));
}
match &server.transport {
McpTransportConfig::Stdio { command, cwd, .. } => {
if !Path::new(command).is_absolute() {
return Err(anyhow!(
"MCP stdio server {name:?} command must be absolute"
));
}
if cwd.as_ref().is_some_and(|path| !path.is_absolute()) {
return Err(anyhow!("MCP stdio server {name:?} cwd must be absolute"));
}
}
McpTransportConfig::Http { url, .. } => validate_http_url(name, url)?,
}
}
Ok(())
}
}
fn validate_http_url(name: &str, raw: &str) -> Result<()> {
let url = reqwest::Url::parse(raw)
.with_context(|| format!("MCP HTTP server {name:?} URL is invalid"))?;
if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() {
return Err(anyhow!(
"MCP HTTP server {name:?} URL may not contain credentials or a fragment"
));
}
let loopback_http =
url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"));
if url.scheme() != "https" && !loopback_http {
return Err(anyhow!(
"MCP HTTP server {name:?} must use HTTPS or loopback HTTP"
));
}
Ok(())
}
impl McpServerConfig {
pub fn startup_timeout(&self) -> Duration {
Duration::from_secs(self.startup_timeout_sec)
}
pub fn tool_timeout(&self) -> Duration {
Duration::from_secs(self.tool_timeout_sec)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_only_the_owned_stdio_and_http_subset() -> Result<()> {
let config = McpRuntimeConfig::from_toml(
r#"
[mcp_servers.local]
command = "C:/mcp/server.exe"
args = ["--stdio"]
startup_timeout_sec = 2
[mcp_servers.remote]
url = "https://example.test/mcp"
bearer_token_env_var = "MCP_TOKEN"
tool_timeout_sec = 4
"#,
)?;
assert!(matches!(
config.server("local")?.transport,
McpTransportConfig::Stdio { .. }
));
assert!(matches!(
config.server("remote")?.transport,
McpTransportConfig::Http { .. }
));
assert!(
McpRuntimeConfig::from_toml("[mcp_servers.bad]\nurl='http://example.test/mcp'")
.is_err()
);
assert!(
McpRuntimeConfig::from_toml(
"[mcp_servers.bad]\nurl='http://localhost.evil.test:8080/mcp'"
)
.is_err()
);
assert!(
McpRuntimeConfig::from_toml("[mcp_servers.bad]\nurl='https://secret@example.test/mcp'")
.is_err()
);
assert!(
McpRuntimeConfig::from_toml("[mcp_servers.bad]\ncommand='x'\nurl='https://x.test'")
.is_err()
);
assert!(
McpRuntimeConfig::from_toml("[mcp_servers.bad]\ncommand='relative-server'").is_err()
);
assert!(
McpRuntimeConfig::from_toml(
"[mcp_servers.bad]\ncommand='C:/server.exe'\ncwd='relative'"
)
.is_err()
);
assert!(
McpRuntimeConfig::from_toml(
"[mcp_servers.bad]\ncommand='C:/server.exe'\ninherit_env=true"
)
.is_err()
);
Ok(())
}
}

View file

@ -0,0 +1,333 @@
//! First-party MCP client edge for Epiphany tool intents.
//!
//! The official RMCP SDK owns MCP protocol behavior. Epiphany owns the strict
//! endpoint policy and translates between MCP cargo and typed tool receipts.
mod config;
mod native_source;
pub use config::{McpRuntimeConfig, McpServerConfig, McpTransportConfig};
pub use native_source::execute_epiphany_source;
use anyhow::{Context, Result, anyhow};
use epiphany_tool_adapter::{
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID, EpiphanyToolInvocationIntent, EpiphanyToolInvocationReceipt,
TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID,
};
use http::{HeaderName, HeaderValue};
use rmcp::{
ServiceExt,
model::CallToolRequestParams,
transport::{
StreamableHttpClientTransport, TokioChildProcess,
streamable_http_client::StreamableHttpClientTransportConfig,
},
};
use serde_json::Value;
use std::collections::HashMap;
use std::process::Stdio;
use std::time::{SystemTime, UNIX_EPOCH};
pub const MCP_CLIENT_NAME: &str = "epiphany-tool-mcp-runtime";
#[derive(Debug, Clone, PartialEq)]
pub struct InvocationOutcome {
pub receipt: EpiphanyToolInvocationReceipt,
/// Protocol-edge cargo. The integration owner decides whether to seal it
/// and which reference, if any, may be exposed in the typed receipt.
pub raw_result: Option<Value>,
}
pub async fn invoke(
intent: &EpiphanyToolInvocationIntent,
config: &McpRuntimeConfig,
) -> InvocationOutcome {
let completed_at = now_utc_string();
let mut receipt = EpiphanyToolInvocationReceipt::new(
format!("receipt-{}-{}", intent.intent_id, unix_millis()),
intent.intent_id.clone(),
intent.adapter.clone(),
intent.server.clone(),
intent.tool_name.clone(),
"failed",
completed_at,
);
let result = invoke_raw(intent, config).await;
match result {
Ok(value) => {
receipt.status = "completed".into();
receipt.result_json = serde_json::to_string(&value).ok();
InvocationOutcome {
receipt,
raw_result: Some(value),
}
}
Err(error) => {
receipt.error = Some(bounded_error(&format!("{error:#}")));
InvocationOutcome {
receipt,
raw_result: None,
}
}
}
}
pub async fn invoke_raw(
intent: &EpiphanyToolInvocationIntent,
config: &McpRuntimeConfig,
) -> Result<Value> {
validate_intent(intent)?;
let server = config.server(&intent.server)?;
let arguments = parse_arguments(&intent.arguments_json)?;
match &server.transport {
McpTransportConfig::Stdio {
command,
args,
env,
cwd,
} => {
invoke_stdio(
server,
command,
args,
env,
cwd.as_deref(),
&intent.tool_name,
arguments,
)
.await
}
McpTransportConfig::Http {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
} => {
invoke_http(
server,
url,
bearer_token_env_var.as_deref(),
http_headers,
env_http_headers,
&intent.tool_name,
arguments,
)
.await
}
}
}
async fn invoke_stdio(
server: &McpServerConfig,
command: &str,
args: &[String],
env: &std::collections::HashMap<String, String>,
cwd: Option<&std::path::Path>,
tool: &str,
arguments: Option<Value>,
) -> Result<Value> {
let mut process = tokio::process::Command::new(command);
process
.args(args)
.env_clear()
.envs(env)
.stderr(Stdio::inherit());
if let Some(cwd) = cwd {
process.current_dir(cwd);
}
#[cfg(windows)]
process.creation_flags(0x08000000);
let transport = TokioChildProcess::new(process).context("starting RMCP child transport")?;
bounded_rmcp_call(server, transport, tool, arguments).await
}
async fn invoke_http(
server: &McpServerConfig,
url: &str,
bearer_env: Option<&str>,
literal: &std::collections::HashMap<String, String>,
from_env: &std::collections::HashMap<String, String>,
tool: &str,
arguments: Option<Value>,
) -> Result<Value> {
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.no_proxy()
.build()
.context("building contained RMCP HTTP client")?;
let mut headers = HashMap::new();
for (name, value) in literal {
headers.insert(
HeaderName::from_bytes(name.as_bytes())?,
HeaderValue::from_str(value)?,
);
}
for (name, variable) in from_env {
headers.insert(
HeaderName::from_bytes(name.as_bytes())?,
HeaderValue::from_str(&std::env::var(variable).with_context(|| {
format!("HTTP header environment variable {variable:?} is absent")
})?)?,
);
}
let mut config =
StreamableHttpClientTransportConfig::with_uri(url.to_string()).custom_headers(headers);
if let Some(variable) = bearer_env {
config = config.auth_header(std::env::var(variable).with_context(|| {
format!("bearer token environment variable {variable:?} is absent")
})?);
}
let transport = StreamableHttpClientTransport::with_client(client, config);
bounded_rmcp_call(server, transport, tool, arguments).await
}
async fn bounded_rmcp_call<T>(
server: &McpServerConfig,
transport: T,
tool: &str,
arguments: Option<Value>,
) -> Result<Value>
where
T: rmcp::transport::Transport<rmcp::RoleClient> + 'static,
{
tokio::time::timeout(
server.startup_timeout() + server.tool_timeout(),
async move {
let service = ().serve(transport).await.context("initializing RMCP client")?;
let invocation = async {
let catalog = service
.peer()
.list_all_tools()
.await
.context("listing RMCP tools")?;
ensure_tool_available(
catalog.iter().map(|candidate| candidate.name.as_ref()),
tool,
)?;
let mut request = CallToolRequestParams::new(tool.to_string());
if let Some(Value::Object(arguments)) = arguments {
request = request.with_arguments(arguments);
}
service
.peer()
.call_tool(request)
.await
.context("calling RMCP tool")
}
.await;
let close = service.cancel().await.context("closing RMCP client");
let result = invocation?;
close?;
serde_json::to_value(result).context("encoding RMCP tool result")
},
)
.await
.map_err(|_| anyhow!("RMCP invocation exceeded bounded whole-call timeout"))?
}
fn ensure_tool_available<'a>(names: impl IntoIterator<Item = &'a str>, tool: &str) -> Result<()> {
if !names.into_iter().any(|candidate| candidate == tool) {
return Err(anyhow!(
"MCP server does not advertise requested tool {tool:?}"
));
}
Ok(())
}
pub fn validate_intent(intent: &EpiphanyToolInvocationIntent) -> Result<()> {
if intent.schema_id != TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID {
return Err(anyhow!("unsupported tool intent schema"));
}
if intent.adapter != EPIPHANY_TOOL_RUNTIME_ADAPTER_ID {
return Err(anyhow!("tool intent targets another adapter"));
}
if intent.intent_id.trim().is_empty()
|| intent.server.trim().is_empty()
|| intent.tool_name.trim().is_empty()
{
return Err(anyhow!("tool intent identity, server, or tool is empty"));
}
Ok(())
}
fn parse_arguments(raw: &str) -> Result<Option<Value>> {
let raw = raw.trim();
if raw.is_empty() || raw == "null" {
return Ok(None);
}
let value: Value = serde_json::from_str(raw)?;
match value {
Value::Object(_) => Ok(Some(value)),
_ => Err(anyhow!("MCP tool arguments must be an object or null")),
}
}
fn bounded_error(value: &str) -> String {
const LIMIT: usize = 2_000;
if value.chars().count() <= LIMIT {
return value.into();
}
value.chars().take(LIMIT).collect::<String>() + "...<truncated>"
}
fn now_utc_string() -> String {
format!("unix-ms:{}", unix_millis())
}
fn unix_millis() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn intent(arguments: &str) -> EpiphanyToolInvocationIntent {
EpiphanyToolInvocationIntent::new(
"intent-1",
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID,
"demo",
"echo",
arguments,
"test",
"prove edge contract",
"now",
)
}
#[test]
fn typed_intent_contract_is_preserved() {
assert!(validate_intent(&intent("{}")).is_ok());
let mut alien = intent("{}");
alien.adapter = "alien".into();
assert!(validate_intent(&alien).is_err());
assert!(parse_arguments("[]").is_err());
}
#[tokio::test]
async fn missing_server_becomes_bounded_typed_failure_receipt() {
let config = McpRuntimeConfig {
mcp_servers: BTreeMap::new(),
};
let outcome = invoke(&intent("{}"), &config).await;
assert_eq!(outcome.receipt.status, "failed");
assert_eq!(outcome.receipt.intent_id, "intent-1");
assert!(outcome.receipt.error.as_deref().unwrap().contains("demo"));
assert!(outcome.raw_result.is_none());
}
#[test]
fn tool_catalog_must_be_complete_and_advertise_target() {
assert!(ensure_tool_available(["wanted"], "wanted").is_ok());
assert!(
ensure_tool_available(["other"], "wanted")
.unwrap_err()
.to_string()
.contains("does not advertise")
);
}
}

View file

@ -0,0 +1,317 @@
use anyhow::{Context, Result, anyhow};
use epiphany_tool_adapter::{
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID, EpiphanyToolInvocationIntent, EpiphanyToolInvocationReceipt,
TOOL_ADAPTER_CAPABILITY_SCHEMA_ID, TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID,
TOOL_ADAPTER_INVOCATION_RECEIPT_SCHEMA_ID, tool_invocation_intent_key,
tool_invocation_receipt_key,
};
use epiphany_tool_mcp_runtime::{
McpRuntimeConfig, execute_epiphany_source, invoke, validate_intent,
};
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
#[tokio::main]
async fn main() -> Result<()> {
match Cli::parse(std::env::args().skip(1).collect())? {
Cli::Run(options) => println!("{}", serde_json::to_string_pretty(&run(options).await?)?),
Cli::Smoke => println!("{}", serde_json::to_string_pretty(&smoke())?),
}
Ok(())
}
enum Cli {
Run(RunOptions),
Smoke,
}
struct RunOptions {
store: PathBuf,
intent_id: String,
mcp_config: Option<PathBuf>,
cwd: Option<PathBuf>,
}
impl Cli {
fn parse(args: Vec<String>) -> Result<Self> {
let (command, rest) = args.split_first().ok_or_else(|| anyhow!(usage()))?;
match command.as_str() {
"smoke" if rest.is_empty() => Ok(Self::Smoke),
"smoke" => Err(anyhow!("smoke accepts no arguments")),
"run" => {
let flags = flags(rest)?;
reject_unknown(&flags, &["store", "intent-id", "mcp-config", "cwd"])?;
Ok(Self::Run(RunOptions {
store: PathBuf::from(required(&flags, "store")?),
intent_id: required(&flags, "intent-id")?.to_string(),
mcp_config: flags.get("mcp-config").map(PathBuf::from),
cwd: flags.get("cwd").map(PathBuf::from),
}))
}
_ => Err(anyhow!(usage())),
}
}
}
async fn run(options: RunOptions) -> Result<RunSummary> {
let mut cache = open_store(&options.store)?;
let intent = cache
.get_required::<EpiphanyToolInvocationIntent>(&tool_invocation_intent_key(
&options.intent_id,
))
.with_context(|| format!("loading tool intent {:?}", options.intent_id))?;
if intent.intent_id != options.intent_id {
return Err(anyhow!("loaded intent identity mismatch"));
}
let receipt = execute_to_receipt(&intent, &options).await;
cache.put(tool_invocation_receipt_key(&intent.intent_id), &receipt)?;
Ok(RunSummary {
adapter: EPIPHANY_TOOL_RUNTIME_ADAPTER_ID.into(),
store: options.store.display().to_string(),
intent_id: intent.intent_id,
receipt_id: receipt.receipt_id,
status: receipt.status,
schemas: schemas(),
})
}
async fn execute_to_receipt(
intent: &EpiphanyToolInvocationIntent,
options: &RunOptions,
) -> EpiphanyToolInvocationReceipt {
let result = async {
validate_intent(intent)?;
if intent.server == "epiphany_source" {
let cwd = match &options.cwd {
Some(path) => path.clone(),
None => std::env::current_dir()?,
};
execute_epiphany_source(intent, &options.store, &cwd)
} else {
let path = options.mcp_config.as_ref().ok_or_else(|| {
anyhow!(
"--mcp-config is required for MCP server {:?}",
intent.server
)
})?;
let config = McpRuntimeConfig::from_path(path)?;
let outcome = invoke(intent, &config).await;
match outcome.raw_result {
Some(value) if outcome.receipt.status == "completed" => Ok(value),
_ => Err(anyhow!(
outcome
.receipt
.error
.unwrap_or_else(|| "MCP invocation failed".into())
)),
}
}
}
.await;
let mut receipt = EpiphanyToolInvocationReceipt::new(
format!("receipt-{}-{}", intent.intent_id, unix_millis()),
intent.intent_id.clone(),
intent.adapter.clone(),
intent.server.clone(),
intent.tool_name.clone(),
if result.is_ok() {
"completed"
} else {
"failed"
},
now(),
);
match result {
Ok(value) => receipt.result_json = serde_json::to_string(&value).ok(),
Err(error) => receipt.error = Some(bound(&format!("{error:#}"), 2_000)),
}
receipt
}
fn open_store(path: &Path) -> Result<cultcache_rs::CultCache> {
let mut cache = epiphany_core::runtime_spine_cache(path)?;
cache.pull_all_backing_stores()?;
Ok(cache)
}
fn flags(args: &[String]) -> Result<BTreeMap<String, String>> {
if !args.len().is_multiple_of(2) {
return Err(anyhow!("each flag requires a value"));
}
let mut result = BTreeMap::new();
for pair in args.chunks_exact(2) {
let name = pair[0]
.strip_prefix("--")
.ok_or_else(|| anyhow!("expected flag, got {:?}", pair[0]))?;
if result.insert(name.into(), pair[1].clone()).is_some() {
return Err(anyhow!("duplicate --{name}"));
}
}
Ok(result)
}
fn required<'a>(flags: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
flags
.get(name)
.map(String::as_str)
.filter(|v| !v.is_empty())
.ok_or_else(|| anyhow!("missing --{name}"))
}
fn reject_unknown(flags: &BTreeMap<String, String>, allowed: &[&str]) -> Result<()> {
if let Some(name) = flags.keys().find(|name| !allowed.contains(&name.as_str())) {
Err(anyhow!("unknown flag --{name}"))
} else {
Ok(())
}
}
fn usage() -> &'static str {
"usage: epiphany-tool-mcp-runtime run --store PATH --intent-id ID [--mcp-config PATH] [--cwd PATH] | smoke"
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RunSummary {
adapter: String,
store: String,
intent_id: String,
receipt_id: String,
status: String,
schemas: BTreeMap<String, String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SmokeSummary {
adapter: String,
status: String,
native_namespace: String,
schemas: BTreeMap<String, String>,
}
fn smoke() -> SmokeSummary {
SmokeSummary {
adapter: EPIPHANY_TOOL_RUNTIME_ADAPTER_ID.into(),
status: "ok".into(),
native_namespace: "epiphany_source".into(),
schemas: schemas(),
}
}
fn schemas() -> BTreeMap<String, String> {
BTreeMap::from([
(
"capability".into(),
TOOL_ADAPTER_CAPABILITY_SCHEMA_ID.into(),
),
(
"intent".into(),
TOOL_ADAPTER_INVOCATION_INTENT_SCHEMA_ID.into(),
),
(
"receipt".into(),
TOOL_ADAPTER_INVOCATION_RECEIPT_SCHEMA_ID.into(),
),
])
}
fn unix_millis() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
}
fn now() -> String {
format!("unix-ms:{}", unix_millis())
}
fn bound(value: &str, limit: usize) -> String {
if value.chars().count() <= limit {
value.into()
} else {
value.chars().take(limit).collect::<String>() + "...<truncated>"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_production_cli_without_legacy_codex_flags() -> Result<()> {
let Cli::Run(options) = Cli::parse(vec![
"run".into(),
"--store".into(),
"body.cc".into(),
"--intent-id".into(),
"i".into(),
"--mcp-config".into(),
"mcp.toml".into(),
])?
else {
panic!()
};
assert_eq!(options.intent_id, "i");
assert!(
Cli::parse(vec![
"run".into(),
"--store".into(),
"x".into(),
"--intent-id".into(),
"i".into(),
"--codex-home".into(),
"x".into()
])
.is_err()
);
Ok(())
}
#[test]
fn smoke_names_first_party_runtime() {
let value = serde_json::to_value(smoke()).unwrap();
assert_eq!(value["adapter"], EPIPHANY_TOOL_RUNTIME_ADAPTER_ID);
assert_eq!(value["nativeNamespace"], "epiphany_source");
assert!(!value.to_string().to_lowercase().contains("codex"));
}
#[tokio::test]
async fn native_source_run_persists_one_typed_receipt_without_mcp_config() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("runtime.cc");
let source = temp.path().join("body.txt");
std::fs::write(&source, "awake\n")?;
epiphany_core::initialize_runtime_spine(
&store,
epiphany_core::RuntimeSpineInitOptions {
runtime_id: "native-tool-test".into(),
display_name: "Native Tool Test".into(),
created_at: "now".into(),
},
)?;
let intent = EpiphanyToolInvocationIntent::new(
"native-read",
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID,
"epiphany_source",
"read_file",
r#"{"path":"body.txt"}"#,
"test",
"prove provider-independent native tools",
"now",
);
let mut cache = open_store(&store)?;
cache.put(tool_invocation_intent_key(&intent.intent_id), &intent)?;
let summary = run(RunOptions {
store: store.clone(),
intent_id: intent.intent_id.clone(),
mcp_config: None,
cwd: Some(temp.path().to_path_buf()),
})
.await?;
assert_eq!(summary.status, "completed");
let cache = open_store(&store)?;
let receipt = cache.get_required::<EpiphanyToolInvocationReceipt>(
&tool_invocation_receipt_key(&intent.intent_id),
)?;
assert_eq!(receipt.adapter, EPIPHANY_TOOL_RUNTIME_ADAPTER_ID);
assert!(receipt.result_json.as_deref().unwrap().contains("awake"));
Ok(())
}
}

View file

@ -0,0 +1,233 @@
use anyhow::{Context, Result, anyhow};
use epiphany_tool_adapter::EpiphanyToolInvocationIntent;
use serde_json::{Value, json};
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
pub fn execute_epiphany_source(
intent: &EpiphanyToolInvocationIntent,
store: &Path,
cwd: &Path,
) -> Result<Value> {
let arguments: Value =
serde_json::from_str(&intent.arguments_json).context("arguments_json is not valid JSON")?;
if !arguments.is_object() {
return Err(anyhow!("epiphany_source arguments must be an object"));
}
match intent.tool_name.as_str() {
"read_file" => read_file(cwd, &arguments),
"git_show" => git_show(cwd, &arguments),
"read_hands_receipt" => read_hands_receipt(store, &arguments),
other => Err(anyhow!("unknown epiphany_source tool {other:?}")),
}
}
fn read_file(cwd: &Path, arguments: &Value) -> Result<Value> {
let requested = required_string(arguments, "path")?;
let start = optional_u64(arguments, "startLine")?.unwrap_or(1).max(1) as usize;
let maximum = optional_u64(arguments, "maxLines")?
.unwrap_or(120)
.clamp(1, 240) as usize;
let path = confined_path(cwd, requested)?;
let reader =
BufReader::new(File::open(&path).with_context(|| format!("reading {}", path.display()))?);
let mut content = Vec::new();
let mut count = 0usize;
for line in reader.lines() {
let line = line.with_context(|| format!("reading {}", path.display()))?;
count += 1;
if count >= start && content.len() < maximum {
content.push(format!("{count}: {}", truncate_chars(&line, 8_192)));
}
}
Ok(
json!({"path":path.display().to_string(),"startLine":start,"maxLines":maximum,"lineCount":count,"content":content.join("\n")}),
)
}
fn git_show(cwd: &Path, arguments: &Value) -> Result<Value> {
let revision = required_string(arguments, "revision")?;
let maximum = optional_u64(arguments, "maxBytes")?
.unwrap_or(16_000)
.clamp(512, 24_000) as usize;
let mut command = Command::new("git");
command
.current_dir(cwd)
.args([
"show",
"--stat",
"--patch",
"--format=medium",
revision,
"--",
])
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if let Some(paths) = arguments.get("paths").and_then(Value::as_array) {
for path in paths.iter().map(|value| {
value
.as_str()
.ok_or_else(|| anyhow!("git_show paths must be strings"))
}) {
command.arg(path?);
}
}
let mut child = command.spawn().context("starting git show")?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow!("git stdout unavailable"))?;
let stderr = child
.stderr
.take()
.ok_or_else(|| anyhow!("git stderr unavailable"))?;
let out = thread::spawn(move || read_retained(stdout, maximum));
let err = thread::spawn(move || read_retained(stderr, 4_000));
let status = child.wait().context("waiting for git show")?;
let stdout = out
.join()
.map_err(|_| anyhow!("git stdout reader panicked"))??;
let stderr = err
.join()
.map_err(|_| anyhow!("git stderr reader panicked"))??;
Ok(
json!({"revision":revision,"status":status.code(),"success":status.success(),"stdout":stdout,"stderr":stderr}),
)
}
fn read_retained(mut input: impl Read, limit: usize) -> Result<String> {
let mut retained = Vec::with_capacity(limit.min(8_192));
let mut buffer = [0u8; 8_192];
let mut truncated = false;
loop {
let count = input.read(&mut buffer)?;
if count == 0 {
break;
}
let available = limit.saturating_sub(retained.len());
retained.extend_from_slice(&buffer[..count.min(available)]);
truncated |= count > available;
}
let mut text = String::from_utf8_lossy(&retained).into_owned();
if truncated {
text.push_str("\n...<truncated>");
}
Ok(text)
}
fn read_hands_receipt(store: &Path, arguments: &Value) -> Result<Value> {
let id = required_string(arguments, "receiptId")?;
match required_string(arguments, "kind")? {
"patch" => {
let r = epiphany_core::runtime_hands_patch_receipt(store, id)?
.ok_or_else(|| anyhow!("Hands patch receipt {id:?} not found"))?;
serde_json::to_value(r).context("encoding Hands patch receipt")
}
"command" => {
let r = epiphany_core::runtime_hands_command_receipt(store, id)?
.ok_or_else(|| anyhow!("Hands command receipt {id:?} not found"))?;
serde_json::to_value(r).context("encoding Hands command receipt")
}
"commit" => {
let r = epiphany_core::runtime_hands_commit_receipt(store, id)?
.ok_or_else(|| anyhow!("Hands commit receipt {id:?} not found"))?;
serde_json::to_value(r).context("encoding Hands commit receipt")
}
other => Err(anyhow!("unsupported Hands receipt kind {other:?}")),
}
}
fn confined_path(cwd: &Path, requested: &str) -> Result<PathBuf> {
let root = cwd
.canonicalize()
.with_context(|| format!("canonicalizing cwd {}", cwd.display()))?;
let requested = PathBuf::from(requested);
let candidate = (if requested.is_absolute() {
requested
} else {
root.join(requested)
})
.canonicalize()
.context("canonicalizing requested path")?;
if !candidate.starts_with(&root) {
return Err(anyhow!("read path escapes workspace"));
}
Ok(candidate)
}
fn required_string<'a>(value: &'a Value, name: &str) -> Result<&'a str> {
value
.get(name)
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| anyhow!("missing required string argument {name:?}"))
}
fn optional_u64(value: &Value, name: &str) -> Result<Option<u64>> {
match value.get(name) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_u64()
.map(Some)
.ok_or_else(|| anyhow!("argument {name:?} must be unsigned")),
}
}
fn truncate_chars(value: &str, limit: usize) -> String {
if value.chars().count() <= limit {
value.into()
} else {
value.chars().take(limit).collect::<String>() + "...<truncated>"
}
}
#[cfg(test)]
mod tests {
use super::*;
use epiphany_tool_adapter::EPIPHANY_TOOL_RUNTIME_ADAPTER_ID;
use std::fs;
fn intent(tool: &str, arguments: &str) -> EpiphanyToolInvocationIntent {
EpiphanyToolInvocationIntent::new(
"i",
EPIPHANY_TOOL_RUNTIME_ADAPTER_ID,
"epiphany_source",
tool,
arguments,
"test",
"test",
"now",
)
}
#[test]
fn reads_only_bounded_workspace_slice() -> Result<()> {
let dir = tempfile::tempdir()?;
fs::write(dir.path().join("body.txt"), "one\ntwo\nthree\nfour\n")?;
let value = execute_epiphany_source(
&intent(
"read_file",
r#"{"path":"body.txt","startLine":2,"maxLines":2}"#,
),
dir.path(),
dir.path(),
)?;
assert_eq!(value["content"], "2: two\n3: three");
assert!(
execute_epiphany_source(
&intent("read_file", r#"{"path":"../escape"}"#),
dir.path(),
dir.path()
)
.is_err()
);
Ok(())
}
#[test]
fn retained_reader_discards_excess_bytes() -> Result<()> {
assert_eq!(read_retained(&b"abcdef"[..], 3)?, "abc\n...<truncated>");
Ok(())
}
}

View file

@ -2762,7 +2762,7 @@ process; coordinator exit zero without its exact receipt fails. The old
source-tree/Cargo swarm wrapper and its `online`, `run`, `run-queue`, `pulse`,
and `epiphany-work` queue authority are outside the live body. Packaging now
requires witnessed sibling roles for swarm, coordinator, model runtime, and the
Codex MCP tool spine.
first-party tool runtime.
Verification must remain at these typed transitions: CAS/replay, store
separation, release witness, child-claim-before-cognition, exact process
@ -3691,3 +3691,23 @@ wiring tests require those exact paths and reject directory-wide custody. Next
install exact a281e38 under both brakes, verify the Idunn restart and old body,
then use only a fresh exact Epiphany successor/request. Seq269 is terminal and
must never be replayed or regranted.
## Native MCP authority cut (2026-07-21)
Tool execution no longer crosses vendored Codex. `epiphany-tool-mcp-runtime`
owns execution of one admitted typed intent and persistence of its typed
receipt. It owns the native `epiphany_source` capability and Epiphany's
endpoint, process, network, timeout, catalog, and receipt policy. The official
RMCP Rust SDK owns MCP lifecycle and wire behavior only. Root-owned
`.epiphany/mcp.toml` configuration may admit foreign stdio or Streamable HTTP
servers; the model cannot configure endpoints. Codex auth, config, MCP, and
app-server are absent from the tool path, the old
`epiphany-tool-codex-mcp-spine` is deleted, and there is no fallback.
This makes tool execution provider-independent, not model execution
provider-neutral. `epiphany-openai-runtime` still defaults to `openai-codex`,
supports OpenAI-shaped transport, and resident policy still carries
`codex_home`. After the braked Yggdrasil deployment transaction is resolved,
the next liberation cut is a provider-neutral model transport and auth policy
that can admit DeepSeek/Kimi without subscription custody. Do not describe the
RMCP cut as subscription independence.

Binary file not shown.

View file

@ -80,8 +80,8 @@ objective:
constraints:
- No frontier-scale training tithe.
- Prefer evidence over vibes; incense is not telemetry.
- Treat Codex as a relatively vanilla bridge to OpenAI and Codex-native runtime/app-server affordances, not a design center: new Epiphany runtime contracts must land native in `epiphany-core`, CultCache, CultMesh, and CultNet first.
- Codex is no longer an Epiphany host to improve. Its acceptable role is to keep doing Codex things, including OpenAI subscription auth/model transport and useful streaming/app-server bridge functions, while Epiphany owns its own state, processes, prompts, scheduler, and policy.
- Treat Codex as a quarantined bridge for the retained OpenAI subscription auth/model transport, not a design center: new Epiphany runtime contracts must land native in `epiphany-core`, CultCache, CultMesh, and CultNet first.
- Codex is no longer an Epiphany host to improve and owns nothing in the tool path. Its retained subscription transport does not provide DeepSeek/Kimi readiness; provider-neutral model transport remains a separate cut.
- Keep persistent state small enough to rehydrate from without drowning the next awakened mind in sacred sludge.
- Grow cognition more quickly than authority: capability increases must preserve explicit permissions, interruption, legibility, and resistance to paternal "safety" cages.
- Speak CultNet, persist CultCache-shaped typed state, and grow the body toward Pure Rust; Python/JSON impurity survives only as named quarantine scaffolding with receipts.
@ -140,7 +140,7 @@ active_subgoals:
- The active priority is Codex starvation and CultNet liberation. Use `notes/codex-starvation-and-cultnet-liberation-plan.md` as the directive and `notes/codex-auth-spine-inventory.md` as the source-grounded keeper list for the retained OpenAI subscription auth/model transport bridge. Classify all Epiphany-relevant JSON contamination, define the native CultNet runtime boundary, keep worker launch/result/selfPatch cargo as typed documents, evacuate Epiphany operator/state/process authority from Codex JSON-RPC, wrap MCP's unavoidable JSON protocol edge in typed Epiphany intent/result/receipt documents, and keep cutting until Epiphany can run its own state and processes without `codex_message_processor.rs` except for bridge compatibility.
- Use `notes/epiphany-anatomy.md` as the canonical anatomy map. Embodied sub-agents are Self, Persona, Imagination, Eyes, Modeling, Hands, and Soul. Body is substrate, Mind is persistent state/state admission, Continuity is recovery/compaction/sleep protocol machinery, and Substrate Gate is substrate access protocol.
- Organ state now has a hard profile split: resident Epiphany sub-agents use lean `work_organ` state, public/person-shaped agents use portable `persona` state, and heartbeat/swarm machinery owns scheduling/coordination physiology. Persona is the Epiphany organ; Persona is the shared GameCult contract for Epiphany Persona, VoidBot repo Personas, and Ghostlight characters. Persona documents carry provenance, required public presentation metadata, `date-time` timestamps, typed `candidateActions`, strict anchored thoughts with non-authoritative extensions, custom enum companion labels, and typed affect subrecords for bonds/status reads/doctrine stances. Work organs must not inherit Persona affect/social-bond/status-read machinery just because the old Ghostlight-derived shape had room for it.
- The Eyes/source-gathering fork exposed by the Mom-ready MVP proof is now landed as a fixed Research lane owned by Eyes. The quarantined Codex MCP spine may execute typed tool intents and emit typed receipts; the model runtime can build and run provider-neutral follow-up turns from those receipts; coordinator run mode passes the quarantined tool adapter into worker runtime with auto-tools enabled by default; worker runtime now enforces max-runtime with one timeout close primitive for both tokio timeout and watchdog paths; inner `openai-worker-*` jobs are opened before async auth/stream waits and sealed with their outer worker on timeout; native status/roles/jobs/coordinator surfaces project failed and completed runtime-linked jobs as terminal without Codex prompt or scheduler authority; direct tiny model-turn transport succeeds; worker requests record request metrics, transport readiness, and sampled raw Responses frame kinds; worker prompts no longer prepend the full shared persistent-memory rite; stream deltas compact before durable storage; live MVP modeling workers complete instead of timing out; stale completed runtime links no longer block replacement launches; jobLaunch validates before opening runtime jobs; completed-but-unreviewable modeling findings now stop for review instead of relaunching the same blind lane; and completed unreviewable modeling findings with verdict `regather-needed` route to `LaunchResearch` instead of relaunching Modeling. Research findings are accepted only when their statePatch is Eyes-shaped: observations, evidence, scratch, and optional investigationCheckpoint, with no graph/planning/objective authority.
- The Eyes/source-gathering fork exposed by the Mom-ready MVP proof is now landed as a fixed Research lane owned by Eyes. The first-party tool runtime executes admitted typed tool intents and emits typed receipts; the typed follow-up document is provider-neutral, while executable model transport remains OpenAI/Codex-only; coordinator run mode passes the tool runtime into worker runtime with auto-tools enabled by default; worker runtime now enforces max-runtime with one timeout close primitive for both tokio timeout and watchdog paths; inner `openai-worker-*` jobs are opened before async auth/stream waits and sealed with their outer worker on timeout; native status/roles/jobs/coordinator surfaces project failed and completed runtime-linked jobs as terminal without Codex prompt or scheduler authority; direct tiny model-turn transport succeeds; worker requests record request metrics, transport readiness, and sampled raw Responses frame kinds; worker prompts no longer prepend the full shared persistent-memory rite; stream deltas compact before durable storage; live MVP modeling workers complete instead of timing out; stale completed runtime links no longer block replacement launches; jobLaunch validates before opening runtime jobs; completed-but-unreviewable modeling findings now stop for review instead of relaunching the same blind lane; and completed unreviewable modeling findings with verdict `regather-needed` route to `LaunchResearch` instead of relaunching Modeling. Research findings are accepted only when their statePatch is Eyes-shaped: observations, evidence, scratch, and optional investigationCheckpoint, with no graph/planning/objective authority.
- The GameCult integrated investment dossier at `E:\Projects\gamecult-site\docs\gamecult_integrated_dossier.tex` raises the Mom-ready bar from local demo to diligence-ready loop. Epiphany must be ready to prove Bifrost-first external work: a human/agent work item or topic originates in Bifrost, Epiphany decomposes and executes through bounded roles, maintainers review artifacts, Bifrost records receipts/credit, and operator-safe public evidence can be shown without exporting private worker/operator/agent context. The concrete readiness asks are fresh-repo Epiphany demo, Bifrost work item/topic/agent transport/receipt/ledger demo, compute spend and accepted-artifact metrics, and a security model for secrets, write permissions, and public/private exports. Discord, VoidBot, repo Personas, and ad hoc scripts must not become shadow governance or reward authorities.
- Bifrost bridge authority is now clarified, enforced, and pushed to `GameCult/Bifrost` upstream `main` through Bifrost commit `72ffa0d` after the bridge chain `445c279`, `23c02be`, `80a5392`, `19222bd`, `675c475`, `f1f9171`, and `72ffa0d`: Epiphany owns swarm execution, repo Body work, branch-local lanes, memory, evidence, and Persona cognition; Bifrost owns GameCult identity, native Bifrost registration/auth, governed external-world crossings, linked-account association, publication/credit/ledger receipts, patronage meaning, and GitHub/Discord/Reddit/future-public-surface bridge policy; Heimdall owns outside-provider OAuth, token custody, and verifiable capability/account/support claims that Bifrost associates with a Bifrost identity. The old Bifrost dispatch bridge was a transitional VoidBot-era worker queue, not the blessed Epiphany launcher. Local bridge tokens are actuator quarantine, not identity. Hosted Bifrost bridge actions store Bifrost identity, Heimdall capability/account reference, Epiphany run id, lane id, and agent identity; Persona/agent Discord, Reddit, or temporary `Other` outside-world actions are denied unless the Bifrost identity normalizes through Bifrost's native identity law, resolves to a registered `UserAccount.NormalizedBifrostIdentity`, that same account has a linked `HeimdallAccountId`, and named surface references are shaped for the requested target surface. GitHub is hooked as a governed bridge and work substrate: the local bridge CLI opens draft PRs and PR comments only through Bifrost gate/receipts, hosted policy requires target repositories and validates Bifrost request/governance provenance for GitHub actions, and GitHub webhooks sync issues, PRs, and reviews into Bifrost work/review state. Bifrost now has a native identity-provider slice: `POST /auth/bifrost/register` creates a Bifrost-owned account without OAuth, assigns `BifrostIdentity` / `NormalizedBifrostIdentity`, signs in with a Bifrost cookie, and leaves membership at `Authenticated` until invite/approval or Heimdall-backed grants elevate it; that Bifrost identity should be enough for most GameCult services that accept Bifrost trust, while GitHub and Heimdall paths now ensure new accounts also receive a Bifrost identity and Heimdall keeps outside-provider account association/token custody. Bifrost's local bridge CLI now exposes `other-request`, a receipt-only `BridgeTargetSurface.Other` / `BridgeActionKind.Other` crossing for future public worlds: it fails closed without `BIFROST_BRIDGE_BASE_URL` and `BIFROST_BRIDGE_TOKEN`, carries Bifrost identity plus Heimdall capability/account reference and Epiphany provenance into the hosted ledger, and deliberately executes no provider transport until the target surface earns a first-class actuator. Patreon support is hooked as Heimdall-signed patronage intake, not Bifrost-owned OAuth: `POST /heimdall/patron-support/events` verifies Heimdall HMAC, resolves the linked `HeimdallAccountId`, records `ExternalPatronProvider.Patreon` support events, writes patron point transactions, and derives current patron tier snapshots.
- Bifrost provider advertisement truth is now synced with the bridge implementation and pushed upstream through Bifrost commits `718ae94` and `fa398ee`: `tools/provider-advertisement.mjs print` names the current bridge action ledger, GitHub webhook work/review sync, and Heimdall patron-support intake endpoints; schemas call bridge action/receipt and patron support current hosted contracts; command boundaries name GitHub draft PR/comment, Discord messages/DMs through the Bifrost gate with Heimdall-linked actor capability, Reddit Persona organizing threads, future-surface `other-request`, and Heimdall-signed Patreon/PayPal support facts; `print-surface` and `print-binding` expose read-only Eve/operator capability sight including `github-bridge`, `github-work-sync`, `discord-bridge`, `reddit-bridge`, `future-surface-bridge`, and `heimdall-patron-support-intake`. Focused Bifrost proof `ProviderAdvertisementTests` passed 2 tests after the Discord/Reddit advertisement hardening, the earlier `ProviderAdvertisementTests|BridgeCliTests` proof passed 32 tests, and the CultCache export path wrote advertisement, operator surface, and interface binding to a temporary witness successfully.
@ -280,7 +280,7 @@ accepted_design:
- Limited native CRRC automation is now wired only at turn-complete safe boundaries: it can submit a compact operation when the read-only coordinator recommends `compactRehydrateReorient` or when a successful pre-compaction checkpoint intervention left a pending compact handoff for the completed turn, and it can launch the fixed `reorient-worker` when the coordinator recommends `launchReorientWorker`. It does not auto-launch modeling or verification, auto-accept findings, promote evidence, edit implementation code, or continue after reviewable semantic results; the rite may carry the stretcher, not declare the patient healed.
- Pre-compaction checkpoint intervention is now wired at token-count boundaries: when a loaded Epiphany thread crosses the existing `shouldPrepareCompaction` pressure threshold during an active turn, the harness steers the active agent once for that turn with a bounded CRRC directive to bank scratch/checkpoint/map/evidence before compaction/reorientation. A successful steer marks a turn-scoped pending compact handoff consumed at clean turn completion; this is banking the fire before the dark, not semantic acceptance, broad scheduling, or automatic implementation continuation.
- Native `epiphany-mvp-status` is the first dogfood operator view: it starts or reads a thread through app-server and renders scene, planning, pressure, reorient, jobs, role result read-backs, reorient result, CRRC recommendation, heartbeat, Persona bubbles, and MVP role lanes as text or machine output without becoming a state store. The old Python status module has been cut; native Rust/CultCache/CultNet surfaces are the product path.
- Native status now exposes the quarantined tool/MCP spine as operator-visible read-only state. Runtime-spine counts typed tool invocation intents, receipts, and pending calls; `runtime_tool_invocation_statuses` derives intent/receipt status rows; `epiphany-runtime-spine status` prints the counts; `epiphany-runtime-spine list-model-requests` prints request tool counts/names; and `epiphany-mvp-status --runtime-store <path>` renders a `tools` section without executing calls, accepting results, or letting Codex prompt machinery steer Epiphany agents. Verification/Soul workers now receive provider-neutral tool definitions on their model request for bounded read-only inspection: `mcp__epiphany_source__read_file`, `mcp__epiphany_source__git_show`, and `mcp__epiphany_source__read_hands_receipt`. The OpenAI/Codex spine lowers those definitions to Responses tools with `tool_choice=required` only on an initial tool-bearing request that has no prior `ToolResult`; model `function_call` output items become typed `epiphany.tool_invocation_intent.v0` documents; and the quarantined tool adapter resolves the built-in `epiphany_source` server directly under workspace-bounded read rules before falling back to Codex MCP. Live dogfood proved this path by producing one source-tool intent and one receipt. Soul should inspect source/artifacts/diffs/Hands receipt bodies through those tool receipts before returning `needs-evidence` for missing inspectability.
- Native status exposes the tool spine as operator-visible read-only state. Runtime-spine counts typed tool invocation intents, receipts, and pending calls; `runtime_tool_invocation_statuses` derives intent/receipt status rows; `epiphany-runtime-spine status` prints the counts; `epiphany-runtime-spine list-model-requests` prints request tool counts/names; and `epiphany-mvp-status --runtime-store <path>` renders a `tools` section without executing calls or accepting results. Verification/Soul workers receive typed tool definitions for bounded read-only inspection: `mcp__epiphany_source__read_file`, `mcp__epiphany_source__git_show`, and `mcp__epiphany_source__read_hands_receipt`. The model runtime lowers those definitions to provider calls and materializes complete calls as typed intents. `epiphany-tool-mcp-runtime` owns execution of one admitted intent and persistence of its typed receipt. Native source capability code plus endpoint/process/network/timeout/catalog/receipt policy are first-party; the official RMCP SDK owns MCP lifecycle and wire behavior only. Root-owned MCP configuration may name foreign servers. Codex auth, config, and app-server are forbidden writers and absent from this path. The deleted Codex MCP spine has no compatibility fallback.
- Model-tool feedback now has a typed continuation seam. `EpiphanyToolInvocationIntent` preserves the exact model `call_id` plus source model request id; provider-neutral and OpenAI request documents can represent assistant `ToolCall` inputs and `ToolResult` inputs; and `epiphany-model-runtime tool-followup` builds a self-contained provider-neutral follow-up request from typed tool receipts by carrying original input, the assistant tool call, and the tool result instead of depending on provider-side `previous_response_id`. ChatGPT Codex rejected `previous_response_id`, so the live continuation invariant is explicit transcript over hidden provider memory. `epiphany-model-runtime tool-followup-turn` derives and runs that continuation through the selected provider in one runtime-owned call, and `epiphany-model-runtime run-worker --auto-tools --tool-adapter-bin <path>` loops tool execution plus follow-up model turns before completing the worker result.
- The `roles` view lens is the harness-native role ownership surface: it projects implementation, Imagination/planning, modeling/checkpoint, verification/review, and reorientation lanes from authoritative typed state, bound jobs, pressure/reorient/CRRC, and worker result status without launching, scheduling, accepting, compacting, or mutating state.
- `thread/epiphany/roleLaunch` and `thread/epiphany/roleResult` are the first explicit role-scoped specialist templates: Imagination/planning, modeling/checkpoint, and verification/review launch through fixed heartbeat-backed bindings with typed runtime-spine receipts and can be read back as reviewable findings from typed runtime-spine job results, while implementation stays owned by the main coding agent and reorientation stays on the CRRC-specific launch/result path.
@ -715,17 +715,18 @@ current_status:
`epiphany.tool_invocation_receipt.v0` documents. Runtime-spine advertises
them as the Epiphany-facing tool contract so MCP discovery/call JSON can
remain protocol-edge cargo instead of scheduler, state, or acceptance
authority. `epiphany-tool-codex-mcp-spine` is the temporary executing
quarantine: it loads one typed invocation intent from CultCache, calls
user-declared Codex MCP through `codex-mcp`, and writes a typed invocation
receipt. It depends on Codex MCP/config/OAuth machinery as transport
scaffolding only; it does not own Epiphany scheduler policy, prompt
authority, durable state, or future provider shape. The future Heimdall or
native tool-auth spine can replace this adapter without changing the
Epiphany-facing intent/receipt contract. `epiphany-model-runtime` now
authority. `epiphany-tool-mcp-runtime` is the first-party executing organ:
it loads one typed invocation intent from CultCache, dispatches explicit
native `epiphany_source` capabilities locally, or calls a root-configured
foreign MCP endpoint through the official `rmcp` SDK, then writes one typed
invocation receipt. Epiphany owns endpoint admission, absolute stdio
process configuration, cleared child environments, HTTPS-or-loopback HTTP,
proxy/redirect refusal, whole-call bounds, tool-catalog verification, and
receipt persistence. RMCP owns MCP lifecycle and wire behavior. Codex owns
neither tool configuration nor execution. `epiphany-model-runtime` now
materializes complete MCP-shaped model tool calls as typed tool invocation
intents, and the Codex MCP spine can consume those intents from the mixed
runtime-spine store and emit typed success/failure receipts.
intents, and the native tool runtime consumes those intents from the mixed
runtime-spine store and emits typed success/failure receipts.
Epiphany agent launch/prompt authority has now been pulled out of the
bridge as well: `epiphany-core::agent_launch` owns specialist prompt
parsing/rendering, role/reorient launch instructions, role binding ids,

View file

@ -275,7 +275,6 @@ $dogfoodRoot = Join-Path $Root ".epiphany-dogfood\$runId"
New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null
New-Item -ItemType Directory -Force -Path $dogfoodRoot | Out-Null
$codexAppServer = Join-Path $TargetDir "debug\codex-app-server.exe"
$statusExe = Join-Path $TargetDir "debug\epiphany-mvp-status.exe"
$operatorRunExe = Join-Path $TargetDir "debug\epiphany-operator-run.exe"
$operatorSnapshotExe = Join-Path $TargetDir "debug\epiphany-operator-snapshot.exe"
@ -290,7 +289,7 @@ $handsActionExe = Join-Path $TargetDir "debug\epiphany-hands-action.exe"
$coordinatorExe = Join-Path $TargetDir "debug\epiphany-mvp-coordinator.exe"
$coordinatorSmokeExe = Join-Path $TargetDir "debug\epiphany-mvp-coordinator-smoke.exe"
$modelRuntimeExe = Join-Path $TargetDir "debug\epiphany-model-runtime.exe"
$toolAdapterExe = Join-Path $TargetDir "debug\epiphany-tool-codex-mcp-spine.exe"
$toolAdapterExe = Join-Path $TargetDir "debug\epiphany-tool-mcp-runtime.exe"
$heartbeatExe = Join-Path $TargetDir "debug\epiphany-heartbeat-store.exe"
$PersonaExe = Join-Path $TargetDir "debug\epiphany-persona-discord.exe"
$PersonaRedditExe = Join-Path $TargetDir "debug\epiphany-persona-reddit.exe"
@ -325,19 +324,10 @@ if ($BifrostTargetRepository -eq "") {
$agentStore = Join-Path $Root "state\agents.msgpack"
$heartbeatStore = Join-Path $Root "state\agent-heartbeats.msgpack"
$runtimeStore = Join-Path $Workspace "state\runtime-spine.msgpack"
$mcpConfig = Join-Path $Workspace ".epiphany\mcp.toml"
$liveRuntimeMode = @("run", "mvp") -contains $Mode
if (-not $SkipBuild) {
if (@("plan", "smoke", "run", "mvp") -contains $Mode) {
Invoke-Checked `
-Label "build Codex app-server compatibility organ" `
-FilePath $cargoExe `
-Arguments @("build", "-p", "codex-app-server", "--manifest-path", ".\vendor\codex\codex-rs\Cargo.toml") `
-WorkingDirectory $Root `
-StdoutPath (Join-Path $artifactRoot "build-codex-app-server.stdout.log") `
-StderrPath (Join-Path $artifactRoot "build-codex-app-server.stderr.log")
}
Invoke-Checked `
-Label "build Epiphany operator binaries" `
-FilePath $cargoExe `
@ -379,9 +369,9 @@ if (-not $SkipBuild) {
-StdoutPath (Join-Path $artifactRoot "build-model-runtime.stdout.log") `
-StderrPath (Join-Path $artifactRoot "build-model-runtime.stderr.log")
Invoke-Checked `
-Label "build quarantined Codex MCP tool adapter" `
-Label "build native Epiphany MCP tool runtime" `
-FilePath $cargoExe `
-Arguments @("build", "--manifest-path", ".\epiphany-tool-codex-mcp-spine\Cargo.toml") `
-Arguments @("build", "--manifest-path", ".\epiphany-tool-mcp-runtime\Cargo.toml") `
-WorkingDirectory $Root `
-StdoutPath (Join-Path $artifactRoot "build-tool-adapter.stdout.log") `
-StderrPath (Join-Path $artifactRoot "build-tool-adapter.stderr.log")
@ -410,7 +400,7 @@ function Format-ServiceExecutionFailedChecks {
}) -join "; ")
}
if (@("plan", "smoke", "run", "mvp") -contains $Mode) {
$requiredBinaries += @($codexAppServer, $coordinatorExe)
$requiredBinaries += @($coordinatorExe)
}
function Assert-SwarmBrakeAllowsLiveRun {
$brakeContextPath = Join-Path $artifactRoot "swarm-brake-preflight.stdout.json"
@ -1483,8 +1473,8 @@ if ($Mode -eq "repo-work-service-plan" -or $Mode -eq "repo-work-service-runbook"
if ($Mode -eq "plan") {
$resultPath = Join-Path $artifactRoot "coordinator-plan.stdout.json"
$planArgs = @(
"--app-server", $codexAppServer,
"--codex-home", $CodexHome,
"--mcp-config", $mcpConfig,
"--cwd", $Workspace,
"--artifact-dir", (Join-Path $dogfoodRoot "coordinator"),
"--runtime-store", $runtimeStore,
@ -1513,7 +1503,6 @@ if ($Mode -eq "smoke") {
-Label "run coordinator smoke" `
-FilePath $coordinatorSmokeExe `
-Arguments @(
"--app-server", $codexAppServer,
"--artifact-root", (Join-Path $dogfoodRoot "coordinator-smoke"),
"--coordinator-exe", $coordinatorExe
) `
@ -1566,11 +1555,11 @@ if ($Mode -eq "mvp") {
if ($liveRuntimeMode) {
$resultPath = Join-Path $artifactRoot "coordinator-run.stdout.json"
$runArgs = @(
"--app-server", $codexAppServer,
"--model-runtime-bin", $modelRuntimeExe,
"--tool-adapter-bin", $toolAdapterExe,
"--model-provider", $modelProvider,
"--codex-home", $CodexHome,
"--mcp-config", $mcpConfig,
"--cwd", $Workspace,
"--artifact-dir", (Join-Path $dogfoodRoot "coordinator"),
"--runtime-store", $runtimeStore,
@ -1670,10 +1659,10 @@ $summary = @"
- workspace: $Workspace
- threadId: $ThreadId
- codexHome: $CodexHome
- mcpConfig: $mcpConfig
- targetDir: $TargetDir
- artifactRoot: $artifactRoot
- dogfoodRoot: $dogfoodRoot
- codexAppServer: $codexAppServer
- statusBinary: $statusExe
- operatorRunBinary: $operatorRunExe
- operatorRunStore: $operatorRunStore