use axum::extract::{Path, Query, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
use serde::Deserialize;
use systemprompt_identifiers::{ArtifactId, TaskId};
use systemprompt_mcp::McpDomainError;
use systemprompt_mcp::services::ui_renderer::MCP_APP_MIME_TYPE;
use systemprompt_mcp::services::ui_renderer::registry::{
create_default_registry, resolve_artifact_type,
};
use systemprompt_models::RequestContext;
use systemprompt_models::api::ApiError;
use systemprompt_runtime::AppContext;
use crate::error::ApiHttpError;
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct ArtifactQueryParams {
pub limit: Option<u32>,
}
pub async fn list_artifacts_by_context(
Extension(req_ctx): Extension<RequestContext>,
State(app_context): State<AppContext>,
Path(context_id): Path<String>,
) -> Result<impl IntoResponse, ApiHttpError> {
tracing::debug!(context_id = %context_id, "Listing artifacts by context");
let context_id_typed = super::parse_context_id(&context_id)?;
let context_repo = app_context.a2a_repositories().contexts.clone();
context_repo
.validate_context_ownership(&context_id_typed, req_ctx.user_id())
.await?;
let artifact_repo = app_context.a2a_repositories().artifacts.clone();
let artifacts = artifact_repo
.get_artifacts_by_context(&context_id_typed)
.await?;
tracing::debug!(
context_id = %context_id,
count = artifacts.len(),
"Artifacts listed"
);
Ok((StatusCode::OK, Json(artifacts)))
}
pub async fn list_artifacts_by_task(
Extension(req_ctx): Extension<RequestContext>,
State(app_context): State<AppContext>,
Path(task_id): Path<String>,
) -> Result<impl IntoResponse, ApiHttpError> {
tracing::debug!(task_id = %task_id, "Listing artifacts by task");
let task_id_typed = TaskId::try_new(&task_id).map_err(ApiError::from)?;
let task_repo = app_context.a2a_repositories().tasks.clone();
task_repo
.validate_task_ownership(&task_id_typed, req_ctx.user_id())
.await?;
let artifact_repo = app_context.a2a_repositories().artifacts.clone();
let artifacts = artifact_repo.get_artifacts_by_task(&task_id_typed).await?;
tracing::debug!(
task_id = %task_id,
count = artifacts.len(),
"Artifacts listed"
);
Ok((StatusCode::OK, Json(artifacts)))
}
pub async fn get_artifact(
Extension(req_ctx): Extension<RequestContext>,
State(app_context): State<AppContext>,
Path(artifact_id): Path<String>,
) -> Result<impl IntoResponse, ApiHttpError> {
tracing::debug!(artifact_id = %artifact_id, "Retrieving artifact");
let artifact_repo = app_context.a2a_repositories().artifacts.clone();
let artifact_id_typed = ArtifactId::try_new(&artifact_id).map_err(ApiError::from)?;
artifact_repo
.validate_artifact_ownership(&artifact_id_typed, req_ctx.user_id())
.await?;
let artifact = artifact_repo
.find_artifact_by_id(&artifact_id_typed)
.await?
.ok_or_else(|| ApiHttpError::not_found(format!("Artifact '{artifact_id}' not found")))?;
tracing::debug!("Artifact retrieved successfully");
Ok((StatusCode::OK, Json(artifact)))
}
pub async fn list_artifacts_by_user(
Extension(req_ctx): Extension<RequestContext>,
State(app_context): State<AppContext>,
Query(params): Query<ArtifactQueryParams>,
) -> Result<impl IntoResponse, ApiHttpError> {
let user_id = req_ctx.user_id();
tracing::debug!(user_id = %user_id, "Listing artifacts by user");
let artifact_repo = app_context.a2a_repositories().artifacts.clone();
let limit = params.limit.map(|l| i32::try_from(l).unwrap_or(i32::MAX));
let artifacts = artifact_repo
.get_artifacts_by_user_id(user_id, limit)
.await?;
tracing::debug!(
user_id = %user_id,
count = artifacts.len(),
"Artifacts listed"
);
Ok((StatusCode::OK, Json(artifacts)))
}
pub async fn get_artifact_ui(
Extension(req_ctx): Extension<RequestContext>,
State(app_context): State<AppContext>,
Path(artifact_id): Path<String>,
) -> Result<Response, ApiHttpError> {
tracing::debug!(artifact_id = %artifact_id, "Rendering artifact as MCP App UI");
let artifact_repo = app_context.a2a_repositories().artifacts.clone();
let artifact_id_typed = ArtifactId::try_new(&artifact_id).map_err(ApiError::from)?;
artifact_repo
.validate_artifact_ownership(&artifact_id_typed, req_ctx.user_id())
.await?;
let artifact = artifact_repo
.find_artifact_by_id(&artifact_id_typed)
.await?
.ok_or_else(|| ApiHttpError::not_found(format!("Artifact '{artifact_id}' not found")))?;
let registry = create_default_registry();
let artifact_type = resolve_artifact_type(&artifact);
if !registry.supports(artifact_type) {
tracing::warn!(artifact_type = %artifact_type, "No UI renderer for artifact type");
return Err(ApiHttpError::bad_request(format!(
"No UI renderer available for artifact type '{artifact_type}'"
)));
}
let ui_resource: systemprompt_mcp::services::ui_renderer::UiResource = registry
.render(&artifact)
.map_err(ArtifactUiError::Render)?;
tracing::debug!(artifact_id = %artifact_id, "Artifact UI rendered successfully");
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, MCP_APP_MIME_TYPE)
.header(
header::CONTENT_SECURITY_POLICY,
ui_resource.csp.to_header_value(),
)
.header(header::X_FRAME_OPTIONS, "SAMEORIGIN")
.body(axum::body::Body::from(ui_resource.html))
.map_err(|e| ArtifactUiError::Response(e).into())
}
#[derive(Debug, thiserror::Error)]
enum ArtifactUiError {
#[error("failed to render artifact UI")]
Render(#[source] McpDomainError),
#[error("failed to build artifact UI response")]
Response(#[source] http::Error),
}
impl From<ArtifactUiError> for ApiHttpError {
fn from(err: ArtifactUiError) -> Self {
let context = match &err {
ArtifactUiError::Render(_) => "Failed to render artifact UI",
ArtifactUiError::Response(_) => "Failed to build response",
};
ApiError::internal(context, err).into()
}
}