CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 27m22s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
439 lines
14 KiB
Rust
439 lines
14 KiB
Rust
use std::{sync::Arc, time::Duration};
|
|
|
|
use axum::{
|
|
Json, Router,
|
|
extract::State,
|
|
http::StatusCode,
|
|
response::{IntoResponse, Response},
|
|
routing::{get, post},
|
|
};
|
|
use crank_core::CoordinationStateStore;
|
|
use crank_registry::{PostgresRegistry, PublishedAgentTool};
|
|
use crank_runtime::{RequestRateLimiter, RuntimeExecutor, SecretCrypto};
|
|
|
|
use serde::Deserialize;
|
|
use serde_json::{Value, json};
|
|
|
|
use tokio::sync::Semaphore;
|
|
|
|
use crate::{
|
|
approval_execution::spawn_approval_recovery,
|
|
auth::SharedMachineCredentialVerifier,
|
|
catalog::PublishedToolCatalog,
|
|
request_context::apply_request_context,
|
|
session::{ActiveSessionMetrics, SharedSessionStore, spawn_session_cleanup},
|
|
transport::AllowedOrigins,
|
|
};
|
|
mod approval_policy;
|
|
/// The private, request-scoped semantic observer of the BUILD-internal harness (spec section 7.2).
|
|
/// It exists only in the crate's own test build: no production API, no global counter.
|
|
#[cfg(test)]
|
|
pub(crate) mod dispatch_observer;
|
|
mod invocation_history;
|
|
pub(crate) mod lifecycle;
|
|
mod metrics;
|
|
mod request;
|
|
mod response;
|
|
mod rmcp_dispatch;
|
|
#[cfg(test)]
|
|
mod rmcp_http;
|
|
#[cfg(test)]
|
|
#[path = "rmcp_http_tests.rs"]
|
|
mod rmcp_http_tests;
|
|
mod rmcp_progress_cancel;
|
|
#[cfg(test)]
|
|
mod rmcp_session_tests;
|
|
#[cfg(test)]
|
|
mod rmcp_tools;
|
|
#[cfg(test)]
|
|
#[path = "rmcp_tools_tests.rs"]
|
|
mod rmcp_tools_tests;
|
|
mod stages;
|
|
mod tool_resolution;
|
|
pub(crate) use self::approval_policy::{
|
|
ApprovalPolicyContext, ApprovalPolicyDecision, maybe_handle_approval_policy,
|
|
};
|
|
pub(crate) use self::response::take_confirmation_token;
|
|
pub(crate) use self::tool_resolution::{resolve_generated_tool, runtime_operation};
|
|
#[cfg(test)]
|
|
use invocation_history::observe_invocation_history_outcome;
|
|
pub(crate) use invocation_history::persist_invocation_for_key;
|
|
pub(super) use invocation_history::{InvocationRecord, persist_invocation};
|
|
|
|
mod approvals;
|
|
mod auth_resolution;
|
|
mod dispatch;
|
|
mod endpoint;
|
|
mod legacy_dispatch;
|
|
mod task_worker;
|
|
mod tasks;
|
|
use self::approvals::{
|
|
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
|
};
|
|
pub(super) use self::auth_resolution::resolve_operation_auth;
|
|
use self::endpoint::{mcp_delete, mcp_get, mcp_post};
|
|
pub use self::task_worker::{TaskWorkerHandler, VerifiedIdempotentWrite};
|
|
pub use self::tasks::{TaskApplication, TaskApplicationError, TaskPrincipal};
|
|
// Test-only import surface: the BUILD-internal `app/tests.rs` module reaches these two
|
|
// through `super`, and the plain lib build does not use them (same pattern as
|
|
// `#[cfg(test)] use invocation_history::observe_invocation_history_outcome;` above).
|
|
#[cfg(test)]
|
|
use self::response::tool_error_response;
|
|
#[cfg(test)]
|
|
use crate::transport::ResponseMode;
|
|
const TRANSPORT_SESSION_TTL_MS: u64 = 86_400_000;
|
|
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 16;
|
|
const SESSION_CLEANUP_INTERVAL: Duration = Duration::from_secs(60);
|
|
|
|
#[derive(Clone)]
|
|
pub(super) struct AppState {
|
|
pub(super) registry: PostgresRegistry,
|
|
pub(super) catalog: PublishedToolCatalog,
|
|
pub(super) runtime: RuntimeExecutor,
|
|
pub(super) api_rate_limiter: RequestRateLimiter,
|
|
/// Immutable artifact reader for published static Resources (Story 3.8). `None` means this
|
|
/// process was not configured with an artifact root; every read then fails closed.
|
|
pub(super) artifact_store: Option<crank_artifacts::ArtifactStore>,
|
|
secret_crypto: SecretCrypto,
|
|
sessions: SharedSessionStore,
|
|
session_metrics: ActiveSessionMetrics,
|
|
session_slots: Arc<Semaphore>,
|
|
pub(super) credential_verifier: SharedMachineCredentialVerifier,
|
|
allowed_origins: AllowedOrigins,
|
|
/// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a
|
|
/// client-scoped level, never a process-global one, and it needs no schema migration.
|
|
pub(super) logging_levels: Arc<crate::protocol::LogLevelStore>,
|
|
/// Story 3.19: the bounded table of the legacy session that currently owns the notification
|
|
/// stream, so one session never broadcasts the same list-change signal into two streams.
|
|
pub(super) signal_streams: Arc<crate::protocol::StreamRegistry>,
|
|
/// Story 3.4: the bounded table of the `tools/call` requests a legacy client can still cancel.
|
|
pub(super) in_flight: Arc<self::lifecycle::InFlightCalls>,
|
|
/// Story 4.2: durable background Tasks over the same registry pool. The public wire stays
|
|
/// synchronous/unsupported; readiness depends on this mandatory store.
|
|
tasks: Arc<TaskApplication>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(super) struct ResolvedToolCall {
|
|
pub(crate) tool: PublishedAgentTool,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Deserialize)]
|
|
pub(super) struct AgentRoutePath {
|
|
pub(super) workspace_slug: String,
|
|
pub(super) agent_slug: String,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Deserialize)]
|
|
struct ApprovalRoutePath {
|
|
workspace_slug: String,
|
|
agent_slug: String,
|
|
approval_id: String,
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn build_app(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
) -> Router {
|
|
build_app_inner(
|
|
registry,
|
|
refresh_interval,
|
|
public_base_url,
|
|
secret_crypto,
|
|
runtime,
|
|
api_rate_limiter,
|
|
coordination_store,
|
|
sessions,
|
|
credential_verifier,
|
|
DEFAULT_MAX_CONCURRENT_SESSIONS,
|
|
false,
|
|
None,
|
|
None,
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn build_app_with_background_workers(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
) -> Router {
|
|
build_app_with_background_workers_and_limits(
|
|
registry,
|
|
refresh_interval,
|
|
public_base_url,
|
|
secret_crypto,
|
|
runtime,
|
|
api_rate_limiter,
|
|
coordination_store,
|
|
sessions,
|
|
credential_verifier,
|
|
DEFAULT_MAX_CONCURRENT_SESSIONS,
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn build_app_with_background_workers_and_limits(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
max_concurrent_sessions: usize,
|
|
) -> Router {
|
|
build_app_inner(
|
|
registry,
|
|
refresh_interval,
|
|
public_base_url,
|
|
secret_crypto,
|
|
runtime,
|
|
api_rate_limiter,
|
|
coordination_store,
|
|
sessions,
|
|
credential_verifier,
|
|
max_concurrent_sessions,
|
|
true,
|
|
None,
|
|
None,
|
|
)
|
|
}
|
|
|
|
/// The production launcher entry point that also serves published static Resources: the app reads
|
|
/// published bytes from the immutable content-addressed `ArtifactStore` of this process.
|
|
///
|
|
/// Callers that do not configure an artifact root keep using the existing constructors above; their
|
|
/// `resources/read` fails closed instead of serving anything from disk.
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn build_app_with_artifacts(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
max_concurrent_sessions: usize,
|
|
artifact_store: crank_artifacts::ArtifactStore,
|
|
) -> Router {
|
|
build_app_inner(
|
|
registry,
|
|
refresh_interval,
|
|
public_base_url,
|
|
secret_crypto,
|
|
runtime,
|
|
api_rate_limiter,
|
|
coordination_store,
|
|
sessions,
|
|
credential_verifier,
|
|
max_concurrent_sessions,
|
|
true,
|
|
Some(artifact_store),
|
|
None,
|
|
)
|
|
}
|
|
|
|
/// Production launcher entry point with the durable Task application entry constructed by the
|
|
/// process composition root from the same registry pool and admission limits as the runtime.
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn build_app_with_artifacts_and_tasks(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
max_concurrent_sessions: usize,
|
|
artifact_store: crank_artifacts::ArtifactStore,
|
|
tasks: Arc<TaskApplication>,
|
|
) -> Router {
|
|
build_app_inner(
|
|
registry,
|
|
refresh_interval,
|
|
public_base_url,
|
|
secret_crypto,
|
|
runtime,
|
|
api_rate_limiter,
|
|
coordination_store,
|
|
sessions,
|
|
credential_verifier,
|
|
max_concurrent_sessions,
|
|
true,
|
|
Some(artifact_store),
|
|
Some(tasks),
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn build_app_inner(
|
|
registry: PostgresRegistry,
|
|
refresh_interval: Duration,
|
|
public_base_url: Option<String>,
|
|
secret_crypto: SecretCrypto,
|
|
runtime: RuntimeExecutor,
|
|
api_rate_limiter: RequestRateLimiter,
|
|
coordination_store: Arc<dyn CoordinationStateStore>,
|
|
sessions: SharedSessionStore,
|
|
credential_verifier: SharedMachineCredentialVerifier,
|
|
max_concurrent_sessions: usize,
|
|
start_background_workers: bool,
|
|
artifact_store: Option<crank_artifacts::ArtifactStore>,
|
|
tasks: Option<Arc<TaskApplication>>,
|
|
) -> Router {
|
|
let session_metrics = ActiveSessionMetrics::start(Arc::clone(&sessions));
|
|
let tasks = tasks.unwrap_or_else(|| {
|
|
let store = crank_registry::PostgresTaskStore::new(
|
|
registry.pool().clone(),
|
|
crank_registry::AdmissionLimits::default(),
|
|
crank_core::AdmissionSchedulerConfig::default(),
|
|
)
|
|
.expect("default admission limits and scheduler weights are valid");
|
|
Arc::new(TaskApplication::new(
|
|
registry.clone(),
|
|
refresh_interval,
|
|
Arc::clone(&coordination_store),
|
|
crank_runtime::TaskService::new(Arc::new(store)),
|
|
))
|
|
});
|
|
let state = Arc::new(AppState {
|
|
registry: registry.clone(),
|
|
catalog: PublishedToolCatalog::new(registry, refresh_interval, coordination_store),
|
|
runtime,
|
|
api_rate_limiter,
|
|
artifact_store,
|
|
secret_crypto,
|
|
sessions,
|
|
session_metrics,
|
|
session_slots: Arc::new(Semaphore::new(max_concurrent_sessions)),
|
|
credential_verifier,
|
|
allowed_origins: AllowedOrigins::new(public_base_url),
|
|
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
|
|
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
|
|
in_flight: Arc::new(lifecycle::InFlightCalls::new(
|
|
lifecycle::MAX_IN_FLIGHT_CALLS,
|
|
)),
|
|
tasks,
|
|
});
|
|
if start_background_workers {
|
|
spawn_approval_recovery(Arc::clone(&state));
|
|
spawn_session_cleanup(
|
|
Arc::clone(&state.sessions),
|
|
state.session_metrics.clone(),
|
|
SESSION_CLEANUP_INTERVAL,
|
|
);
|
|
}
|
|
|
|
Router::new()
|
|
.route("/health", get(health))
|
|
.route("/ready", get(readiness))
|
|
.route(
|
|
"/v1/{workspace_slug}/{agent_slug}",
|
|
get(mcp_get).post(mcp_post).delete(mcp_delete),
|
|
)
|
|
.route(
|
|
"/v1/{workspace_slug}/{agent_slug}/approvals",
|
|
get(list_pending_approvals),
|
|
)
|
|
.route(
|
|
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
|
|
post(approve_request),
|
|
)
|
|
.route(
|
|
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
|
|
get(get_approval_request),
|
|
)
|
|
.route(
|
|
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
|
|
post(deny_request),
|
|
)
|
|
.with_state(state)
|
|
.layer(axum::middleware::from_fn(apply_request_context))
|
|
.layer(axum::middleware::from_fn(
|
|
crank_observability::record_http_request,
|
|
))
|
|
}
|
|
|
|
async fn health() -> Json<Value> {
|
|
Json(json!({
|
|
"service": "mcp-server",
|
|
"status": "ok"
|
|
}))
|
|
}
|
|
|
|
async fn readiness(State(state): State<Arc<AppState>>) -> Response {
|
|
let postgres_ready = state.registry.ping().await.is_ok();
|
|
// Story 4.1: admission state is a mandatory dependency of every execution, so readiness must
|
|
// reflect it rather than reporting ready on a bare `select 1`.
|
|
let admission_ready = state.registry.execution_admission_health().await.is_ok();
|
|
// Story 4.2: the durable Task store is mandatory for a durable acceptance acknowledgement.
|
|
let durable_tasks_ready = state.tasks.health().await.is_ok();
|
|
if postgres_ready && admission_ready && durable_tasks_ready {
|
|
return Json(json!({
|
|
"service": "mcp-server",
|
|
"status": "ready",
|
|
"checks": {
|
|
"postgres": "ready",
|
|
"execution_admission": "ready",
|
|
"durable_tasks": "ready"
|
|
}
|
|
}))
|
|
.into_response();
|
|
}
|
|
let mut checks = serde_json::Map::new();
|
|
checks.insert(
|
|
"postgres".to_owned(),
|
|
json!(if postgres_ready { "ready" } else { "not_ready" }),
|
|
);
|
|
checks.insert(
|
|
"execution_admission".to_owned(),
|
|
json!(if admission_ready {
|
|
"ready"
|
|
} else {
|
|
"not_ready"
|
|
}),
|
|
);
|
|
checks.insert(
|
|
"durable_tasks".to_owned(),
|
|
json!(if durable_tasks_ready {
|
|
"ready"
|
|
} else {
|
|
"not_ready"
|
|
}),
|
|
);
|
|
(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
Json(json!({
|
|
"service": "mcp-server",
|
|
"status": "not_ready",
|
|
"checks": checks,
|
|
"error": "a mandatory dependency is unavailable"
|
|
})),
|
|
)
|
|
.into_response()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|