Skip to main content

agentmux_srv/server/app_api/
dev_server.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/agent/dev_server/register` — backs the `RegisterDevServer`
5//! MCP tool. See docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.
6//!
7//! Identity is verified the same way `ClosePane`/`UIClick`/`UIQuery` do
8//! (`ui_handlers::verified_block_id`) — the calling agent proves it IS
9//! `auth.agent_id` via its own `AGENTMUX_JEKT_KEY` signature; there is no
10//! client-supplied agent id to spoof. The container's internal dev-proxy
11//! network address is then resolved server-side from THAT agent's own
12//! container (`ContainerManager::agent_network_ip`) — never a
13//! client-supplied address, so there is nothing left to spoof there either.
14
15use axum::extract::State;
16use axum::http::StatusCode;
17use axum::response::IntoResponse;
18use axum::Json;
19use serde_json::json;
20
21use agentmux_common::api_types::{RegisterDevServerRequest, RegisterDevServerResponse};
22
23use crate::backend::dev_keepalive::{self, clean_command, clean_dir, route_target, route_when_listening, start, wait_listening, RouteError, Spec};
24
25use super::AppState;
26
27pub(crate) async fn handle_register_dev_server(
28    State(state): State<AppState>,
29    caller: Option<axum::Extension<crate::server::caller::Caller>>,
30    Json(req): Json<RegisterDevServerRequest>,
31) -> impl IntoResponse {
32    // Verifies `req.auth`'s signature against the claimed agent_id's own key on file; the pane it
33    // proves is the one whose container this registers. See this module's doc comment.
34    let block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
35        Ok(b) => b,
36        Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
37    };
38    let agent_id = req.auth.agent_id.clone();
39
40    let project = req.project.trim().to_lowercase();
41    if project.is_empty() {
42        return (
43            StatusCode::BAD_REQUEST,
44            Json(json!({ "error": "project must not be empty" })),
45        )
46            .into_response();
47    }
48    // `project` becomes a DNS label in `<project>-<agent>.localhost` (see
49    // `DevProxyRegistry::routing_key`) — validate it as one instead of only
50    // checking non-empty. An unvalidated value containing e.g. '.' or
51    // whitespace would previously register successfully and hand the caller
52    // back a URL that can never actually route, discovered only when they
53    // tried to open it. reagent P2, PR #3439.
54    let is_hostname_label = !project.is_empty()
55        && project.len() <= 63
56        && !project.starts_with('-')
57        && !project.ends_with('-')
58        && project
59            .bytes()
60            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
61    if !is_hostname_label {
62        return (
63            StatusCode::BAD_REQUEST,
64            Json(json!({
65                "error": "project must be a valid hostname label: lowercase \
66                          letters, digits, and hyphens only, not starting or \
67                          ending with a hyphen, 63 characters or fewer"
68            })),
69        )
70            .into_response();
71    }
72    if req.port == 0 {
73        return (
74            StatusCode::BAD_REQUEST,
75            Json(json!({ "error": "port must be nonzero" })),
76        )
77            .into_response();
78    }
79
80    let Some(cm) = state.container_manager.get().await else {
81        return (
82            StatusCode::SERVICE_UNAVAILABLE,
83            Json(json!({
84                "error": "Docker is not available — RegisterDevServer only works from a \
85                          container-type agent's own container"
86            })),
87        )
88            .into_response();
89    };
90
91    // Named from the pane's `agentId` (the definition's uuid), as the launch path names it; the
92    // slug in `auth.agent_id` names no container.
93    let Some(container_name) = container_of_pane(&state, &block_id) else {
94        return (
95            StatusCode::NOT_FOUND,
96            Json(json!({
97                "error": "RegisterDevServer only works from inside a container-type agent's own container"
98            })),
99        )
100            .into_response();
101    };
102    // With a command, AgentMux starts the server if nothing is listening yet and keeps it up (`dev_keepalive`).
103    let keep = match req.command.as_deref() {
104        None => None,
105        Some(command) => {
106            let spec = clean_command(command).and_then(|command| {
107                let dir = clean_dir(req.dir.as_deref())?;
108                Ok(Spec { agent_id: agent_id.clone(), container: container_name.clone(), project: project.clone(), port: req.port, command, dir, seen: 0 })
109            });
110            match spec {
111                Ok(s) => Some(s),
112                Err(e) => return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response(),
113            }
114        }
115    };
116    // Room for it first, so a refusal leaves nothing started or registered. A server that listens within a request's
117    // patience is registered now; a slower one is registered when it does listen.
118    let mut starting = false;
119    if let Some(spec) = &keep {
120        if let Err(e) = dev_keepalive::store().can_keep(spec) {
121            return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response();
122        }
123        if cm.agent_network_ip(&container_name).await.is_some() {
124            if let Err(e) = start(&cm, spec, false).await {
125                return (StatusCode::BAD_GATEWAY, Json(json!({ "error": e }))).into_response();
126            }
127            starting = !wait_listening(&cm, spec, std::time::Duration::from_secs(6)).await;
128        }
129    }
130    if let (true, Some(spec)) = (starting, &keep) {
131        // Kept before the task that routes it can look, so it can tell the project is still wanted.
132        if let Err(e) = remember(&keep, &container_name, &project) {
133            return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response();
134        }
135        route_when_listening(&cm, spec.clone());
136    } else {
137        // Where the proxy reaches it. On Linux the container's own address; where the daemon runs in a VM
138        // (Docker Desktop) that address is not routable from here, so the dev relay joins the two.
139        let target = match route_target(&cm, &container_name, req.port).await {
140            Ok(t) => t,
141            Err(RouteError::NoContainer) => {
142                return (
143                    StatusCode::NOT_FOUND,
144                    Json(json!({
145                        "error": format!(
146                            "no running container found for agent {agent_id:?} on the dev-proxy \
147                             network — RegisterDevServer only works from inside a container-type \
148                             agent's own container"
149                        )
150                    })),
151                )
152                    .into_response();
153            }
154            Err(RouteError::Relay(e)) => {
155                return (StatusCode::BAD_GATEWAY, Json(json!({ "error": format!("the dev proxy's relay is not available: {e}") }))).into_response();
156            }
157            Err(RouteError::Address(e)) => {
158                return (StatusCode::BAD_REQUEST, Json(json!({ "error": format!("invalid address {e}") }))).into_response();
159            }
160        };
161        state.dev_proxy.register_from(&project, &agent_id, Some(&container_name), target).await;
162        if let Err(e) = remember(&keep, &container_name, &project) {
163            return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response();
164        }
165    }
166    let url = browse_url(&project, &agent_id);
167    (StatusCode::OK, Json(RegisterDevServerResponse { url, starting })).into_response()
168}
169
170/// What a browser should be pointed at. Lowercased to match the actual routing key
171/// (`DevProxyRegistry::routing_key` lowercases both halves), not necessarily `agent_id`'s on-disk casing. The
172/// port is the one the proxy bound, which is not 8090 when another instance on this host holds it.
173fn browse_url(project: &str, agent_id: &str) -> String {
174    format!("http://{project}-{}.localhost:{}", agent_id.to_lowercase(), crate::backend::dev_proxy::port())
175}
176
177/// What is kept up for `project` in `container` after this registration: the spec if there is a command; registered
178/// again without one, nothing.
179fn remember(keep: &Option<Spec>, container: &str, project: &str) -> Result<(), String> {
180    match keep {
181        Some(spec) => dev_keepalive::store().keep(spec.clone()),
182        None => {
183            dev_keepalive::store().drop_project(container, project);
184            Ok(())
185        }
186    }
187}
188
189/// The container the verified pane `block_id` runs in.
190fn container_of_pane(state: &AppState, block_id: &str) -> Option<String> {
191    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
192    crate::server::agent_resources::container_of(&block)
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    fn pane(state: &AppState, meta: &[(&str, &str)]) -> String {
200        let meta = meta.iter().map(|(k, v)| (k.to_string(), json!(v))).collect();
201        let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
202        state.mstore.insert(&mut block).unwrap();
203        block.oid
204    }
205
206    #[tokio::test]
207    async fn the_container_is_named_from_the_panes_definition_id_not_the_slug() {
208        let state = crate::server::tests::test_state();
209        let block = pane(&state, &[("agentMode", "container"), ("agentId", "5d2c7e1a-0000-4000-8000-000000000001")]);
210        assert_eq!(container_of_pane(&state, &block).as_deref(), Some("agentmux-5d2c7e1a-0000-4000-8000-000000000001"));
211    }
212
213    #[tokio::test]
214    async fn a_host_agent_or_an_unknown_pane_has_no_container() {
215        let state = crate::server::tests::test_state();
216        let host = pane(&state, &[("agentMode", "host"), ("agentId", "lark")]);
217        assert_eq!(container_of_pane(&state, &host), None);
218        assert_eq!(container_of_pane(&state, "no-such-pane"), None);
219    }
220}