From 563e17c3df848d349cece51ef44e84a3ae57db02 Mon Sep 17 00:00:00 2001 From: "a.tolmachev" Date: Tue, 31 Mar 2026 15:48:09 +0300 Subject: [PATCH] feat: add platform key usage to mcp auth --- Cargo.lock | 2 + TASKS.md | 15 +- apps/mcp-server/Cargo.toml | 2 + apps/mcp-server/src/app.rs | 89 +++++++++++- apps/mcp-server/src/main.rs | 195 ++++++++++++++++++++++++-- apps/ui/html/api-keys.html | 10 +- apps/ui/js/api-keys.js | 6 +- crates/crank-registry/src/postgres.rs | 56 ++++++++ docs/admin-api.md | 1 + docs/alpine-ui-integration-plan.md | 4 +- docs/mcp-interface.md | 13 ++ 11 files changed, 363 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9d4a04..402bd99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1168,6 +1168,7 @@ name = "mcp-server" version = "0.1.0" dependencies = [ "axum", + "base64", "crank-adapter-grpc", "crank-core", "crank-mapping", @@ -1177,6 +1178,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", "sqlx", "time", "tokio", diff --git a/TASKS.md b/TASKS.md index d932a94..e17b96b 100644 --- a/TASKS.md +++ b/TASKS.md @@ -2,15 +2,14 @@ ## Current -### `feat/demo-assets` +### `feat/platform-key-usage` -Status: in_progress +Status: completed DoD: -- project has an idempotent PostgreSQL demo seed for live UI screens -- demo seed fills workspaces, memberships, invitations, operations, agents, keys and usage -- seed is controlled by env and does not live in migrations -- docs explain how to enable and use demo data +- platform API keys authenticate real machine access +- `last_used_at` updates from successful platform key usage +- UI API keys page reflects honest runtime usage rather than seed-only metadata ## Next @@ -18,6 +17,4 @@ DoD: ## Backlog -- `feat/current-workspace-session-model` -- `feat/agent-lifecycle-polish` -- `feat/platform-key-usage` +- `feat/alpine-polish` diff --git a/apps/mcp-server/Cargo.toml b/apps/mcp-server/Cargo.toml index 8d031f9..6f419a6 100644 --- a/apps/mcp-server/Cargo.toml +++ b/apps/mcp-server/Cargo.toml @@ -7,12 +7,14 @@ version.workspace = true [dependencies] axum.workspace = true +base64.workspace = true crank-core = { path = "../../crates/crank-core" } crank-registry = { path = "../../crates/crank-registry" } crank-runtime = { path = "../../crates/crank-runtime" } crank-schema = { path = "../../crates/crank-schema" } serde.workspace = true serde_json.workspace = true +sha2.workspace = true time.workspace = true tokio = { workspace = true, features = ["sync"] } tracing.workspace = true diff --git a/apps/mcp-server/src/app.rs b/apps/mcp-server/src/app.rs index a1f5c5d..8a980b3 100644 --- a/apps/mcp-server/src/app.rs +++ b/apps/mcp-server/src/app.rs @@ -8,18 +8,21 @@ use axum::{ extract::{Path, State}, http::{ HeaderMap, HeaderValue, StatusCode, - header::{self, ACCEPT}, + header::{self, ACCEPT, AUTHORIZATION}, }, response::{IntoResponse, Response}, routing::get, }; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use crank_core::{ InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus, + PlatformApiKeyScope, }; use crank_registry::{CreateInvocationLogRequest, PostgresRegistry, PublishedAgentTool}; use crank_runtime::{RuntimeError, RuntimeExecutor, RuntimeOperation}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use time::{OffsetDateTime, format_description::well_known::Rfc3339}; use crate::{ @@ -106,6 +109,12 @@ async fn mcp_delete( State(state): State>, headers: HeaderMap, ) -> Response { + if let Err(status) = + require_platform_api_key(&state, &path, &headers, PlatformApiKeyScope::Read).await + { + return status.into_response(); + } + match session_id_from_headers(&headers) { Ok(Some(session_id)) => match state.sessions.get(&session_id).await { Some(session) @@ -149,6 +158,14 @@ async fn mcp_post( Err(status) => return status.into_response(), }; + let required_scope = match method_name(&message) { + Some("tools/call") => PlatformApiKeyScope::Write, + _ => PlatformApiKeyScope::Read, + }; + if let Err(status) = require_platform_api_key(&state, &path, &headers, required_scope).await { + return status.into_response(); + } + match method_name(&message) { Some("initialize") if is_request(&message) => { handle_initialize(state, &path, &message).await @@ -467,6 +484,71 @@ async fn require_initialized_session( Ok(session) } +async fn require_platform_api_key( + state: &Arc, + path: &AgentRoutePath, + headers: &HeaderMap, + required_scope: PlatformApiKeyScope, +) -> Result<(), StatusCode> { + let secret = bearer_token(headers).ok_or(StatusCode::UNAUTHORIZED)?; + let secret_hash = hash_access_secret(secret); + let Some(api_key) = state + .registry + .get_platform_api_key_by_secret_for_workspace_slug(&path.workspace_slug, &secret_hash) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + else { + return Err(StatusCode::UNAUTHORIZED); + }; + + if !allows_scope(&api_key.api_key.scopes, required_scope) { + return Err(StatusCode::FORBIDDEN); + } + + let used_at = OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .registry + .touch_platform_api_key(&api_key.api_key.workspace_id, &api_key.api_key.id, &used_at) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(()) +} + +fn bearer_token(headers: &HeaderMap) -> Option<&str> { + let value = headers.get(AUTHORIZATION)?.to_str().ok()?; + let (scheme, token) = value.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("Bearer") || token.is_empty() { + return None; + } + + Some(token) +} + +fn allows_scope(scopes: &[PlatformApiKeyScope], required_scope: PlatformApiKeyScope) -> bool { + match required_scope { + PlatformApiKeyScope::Read => scopes.iter().any(|scope| { + matches!( + scope, + PlatformApiKeyScope::Read + | PlatformApiKeyScope::Write + | PlatformApiKeyScope::Deploy + ) + }), + PlatformApiKeyScope::Write => scopes.iter().any(|scope| { + matches!( + scope, + PlatformApiKeyScope::Write | PlatformApiKeyScope::Deploy + ) + }), + PlatformApiKeyScope::Deploy => scopes + .iter() + .any(|scope| matches!(scope, PlatformApiKeyScope::Deploy)), + } +} + fn validate_origin( allowed_origins: &AllowedOrigins, headers: &HeaderMap, @@ -611,6 +693,11 @@ fn runtime_error_code(error: &RuntimeError) -> &'static str { } } +fn hash_access_secret(secret: &str) -> String { + let digest = Sha256::digest(secret.as_bytes()); + URL_SAFE_NO_PAD.encode(digest) +} + fn json_response( status: StatusCode, payload: Value, diff --git a/apps/mcp-server/src/main.rs b/apps/mcp-server/src/main.rs index f66de57..12617a3 100644 --- a/apps/mcp-server/src/main.rs +++ b/apps/mcp-server/src/main.rs @@ -49,19 +49,22 @@ mod tests { }; use axum::{Json, Router, http::header, routing::post}; + use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use crank_adapter_grpc::test_support as grpc_test_support; use crank_core::{ Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, DescriptorId, ExecutionConfig, GraphqlOperationType, GraphqlTarget, GrpcTarget, HttpMethod, Operation, - OperationId, OperationStatus, Protocol, RestTarget, Target, ToolDescription, WorkspaceId, + OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope, + PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription, WorkspaceId, }; use crank_mapping::{MappingRule, MappingSet}; use crank_registry::{ - CreateAgentRequest, ListInvocationLogsQuery, PostgresRegistry, PublishAgentRequest, - PublishRequest, + CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry, + PublishAgentRequest, PublishRequest, }; use crank_schema::{Schema, SchemaKind}; use serde_json::{Value, json}; + use sha2::{Digest, Sha256}; use sqlx::{Executor, postgres::PgPoolOptions}; use tokio::net::TcpListener; @@ -96,6 +99,12 @@ mod tests { .await .unwrap(); publish_agent_for_operation(®istry, &operation, "sales-rest").await; + let api_key = create_platform_api_key( + ®istry, + "mcp-rest", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; let base_url = spawn_mcp_server(build_app( registry.clone(), @@ -105,11 +114,12 @@ mod tests { .await; let client = reqwest::Client::new(); let mcp_url = agent_mcp_url(&base_url, "sales-rest"); - let initialized_session = initialize_session(&client, &mcp_url).await; + let initialized_session = initialize_session(&client, &mcp_url, &api_key).await; let tools = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -122,6 +132,7 @@ mod tests { let call_result = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -165,6 +176,12 @@ mod tests { ); assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok); assert_eq!(logs[0].log.tool_name, "crm_create_lead"); + + let keys = registry + .list_platform_api_keys(&test_workspace_id()) + .await + .unwrap(); + assert!(keys[0].api_key.last_used_at.is_some()); } #[tokio::test] @@ -188,6 +205,12 @@ mod tests { .await .unwrap(); publish_agent_for_operation(®istry, &operation, "sales-graphql").await; + let api_key = create_platform_api_key( + ®istry, + "mcp-graphql", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; let base_url = spawn_mcp_server(build_app( registry, @@ -197,11 +220,12 @@ mod tests { .await; let client = reqwest::Client::new(); let mcp_url = agent_mcp_url(&base_url, "sales-graphql"); - let initialized_session = initialize_session(&client, &mcp_url).await; + let initialized_session = initialize_session(&client, &mcp_url, &api_key).await; let call_result = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -245,6 +269,12 @@ mod tests { .await .unwrap(); publish_agent_for_operation(®istry, &operation, "sales-grpc").await; + let api_key = create_platform_api_key( + ®istry, + "mcp-grpc", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; let base_url = spawn_mcp_server(build_app( registry, @@ -254,11 +284,12 @@ mod tests { .await; let client = reqwest::Client::new(); let mcp_url = agent_mcp_url(&base_url, "sales-grpc"); - let initialized_session = initialize_session(&client, &mcp_url).await; + let initialized_session = initialize_session(&client, &mcp_url, &api_key).await; let call_result = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -284,6 +315,9 @@ mod tests { #[tokio::test] async fn requires_initialized_notification_before_tool_methods() { let registry = test_registry().await; + publish_agent_with_bindings(®istry, "sales-init", vec![]).await; + let api_key = + create_platform_api_key(®istry, "mcp-init", &[PlatformApiKeyScope::Read]).await; let base_url = spawn_mcp_server(build_app( registry, Duration::from_millis(0), @@ -295,6 +329,7 @@ mod tests { let initialize_response = client .post(&mcp_url) .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) .json(&json!({ "jsonrpc": "2.0", "id": 1, @@ -316,6 +351,7 @@ mod tests { let tools_list = client .post(&mcp_url) .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Session-Id", session_id) .header("MCP-Protocol-Version", "2025-11-25") .json(&json!({ @@ -346,11 +382,18 @@ mod tests { .await; let client = reqwest::Client::new(); let mcp_url = agent_mcp_url(&base_url, "sales-refresh"); - let initialized_session = initialize_session(&client, &mcp_url).await; + let api_key = create_platform_api_key( + ®istry, + "mcp-refresh", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; + let initialized_session = initialize_session(&client, &mcp_url, &api_key).await; let before_publish = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -381,6 +424,7 @@ mod tests { let after_publish = post_jsonrpc( &client, &mcp_url, + &api_key, Some(&initialized_session), json!({ "jsonrpc": "2.0", @@ -434,6 +478,12 @@ mod tests { vec![binding_for_operation(&operation_b)], ) .await; + let api_key = create_platform_api_key( + ®istry, + "mcp-agents", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; let base_url = spawn_mcp_server(build_app( registry, @@ -444,12 +494,13 @@ mod tests { let client = reqwest::Client::new(); let agent_a_url = agent_mcp_url(&base_url, "sales-a"); let agent_b_url = agent_mcp_url(&base_url, "sales-b"); - let session_a = initialize_session(&client, &agent_a_url).await; - let session_b = initialize_session(&client, &agent_b_url).await; + let session_a = initialize_session(&client, &agent_a_url, &api_key).await; + let session_b = initialize_session(&client, &agent_b_url, &api_key).await; let tools_a = post_jsonrpc( &client, &agent_a_url, + &api_key, Some(&session_a), json!({ "jsonrpc": "2.0", @@ -462,6 +513,7 @@ mod tests { let tools_b = post_jsonrpc( &client, &agent_b_url, + &api_key, Some(&session_b), json!({ "jsonrpc": "2.0", @@ -476,10 +528,97 @@ mod tests { assert_eq!(tools_b["result"]["tools"][0]["name"], "crm_update_lead"); } - async fn initialize_session(client: &reqwest::Client, mcp_url: &str) -> String { + #[tokio::test] + async fn rejects_initialize_without_platform_api_key() { + let registry = test_registry().await; + publish_agent_with_bindings(®istry, "sales-auth", vec![]).await; + let base_url = spawn_mcp_server(build_app( + registry, + Duration::from_millis(0), + Some("https://crank.example.com".to_owned()), + )) + .await; + let client = reqwest::Client::new(); + let response = client + .post(agent_mcp_url(&base_url, "sales-auth")) + .header(header::ACCEPT, "application/json, text/event-stream") + .json(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-11-25" + } + })) + .send() + .await + .unwrap(); + + assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn rejects_tool_call_with_read_only_platform_api_key() { + let registry = test_registry().await; + let upstream_base_url = spawn_upstream_server().await; + let operation = test_operation(&upstream_base_url, "crm_read_only"); + + registry + .create_operation(&test_workspace_id(), &operation, Some("alice")) + .await + .unwrap(); + registry + .publish_operation(PublishRequest { + workspace_id: &test_workspace_id(), + operation_id: &operation.id, + version: 1, + published_at: "2026-03-26T10:00:00Z", + published_by: Some("alice"), + }) + .await + .unwrap(); + publish_agent_for_operation(®istry, &operation, "sales-read-only").await; + let api_key = + create_platform_api_key(®istry, "mcp-read", &[PlatformApiKeyScope::Read]).await; + + let base_url = spawn_mcp_server(build_app( + registry, + Duration::from_millis(0), + Some("https://crank.example.com".to_owned()), + )) + .await; + let client = reqwest::Client::new(); + let mcp_url = agent_mcp_url(&base_url, "sales-read-only"); + let initialized_session = initialize_session(&client, &mcp_url, &api_key).await; + let response = client + .post(&mcp_url) + .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) + .header("MCP-Session-Id", initialized_session) + .header("MCP-Protocol-Version", "2025-11-25") + .json(&json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "crm_read_only", + "arguments": { + "email": "user@example.com" + } + } + })) + .send() + .await + .unwrap(); + + assert_eq!(response.status(), reqwest::StatusCode::FORBIDDEN); + } + + async fn initialize_session(client: &reqwest::Client, mcp_url: &str, api_key: &str) -> String { let initialize_response = client .post(mcp_url) .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) .json(&json!({ "jsonrpc": "2.0", "id": 1, @@ -502,6 +641,7 @@ mod tests { let initialized_response = client .post(mcp_url) .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Session-Id", &session_id) .header("MCP-Protocol-Version", "2025-11-25") .json(&json!({ @@ -521,12 +661,14 @@ mod tests { async fn post_jsonrpc( client: &reqwest::Client, mcp_url: &str, + api_key: &str, session_id: Option<&str>, payload: Value, ) -> Value { let mut request = client .post(mcp_url) .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Protocol-Version", "2025-11-25"); if let Some(session_id) = session_id { @@ -543,6 +685,39 @@ mod tests { .unwrap() } + async fn create_platform_api_key( + registry: &PostgresRegistry, + name: &str, + scopes: &[PlatformApiKeyScope], + ) -> String { + let secret = format!("crk_{}_{}", name, uuid::Uuid::now_v7().simple()); + let api_key = PlatformApiKey { + id: PlatformApiKeyId::new(format!("pk_{name}")), + workspace_id: test_workspace_id(), + name: name.to_owned(), + prefix: secret.chars().take(16).collect(), + scopes: scopes.to_vec(), + status: PlatformApiKeyStatus::Active, + created_at: "2026-03-26T10:00:00Z".to_owned(), + last_used_at: None, + }; + + registry + .create_platform_api_key(CreatePlatformApiKeyRequest { + api_key: &api_key, + secret_hash: &hash_access_secret(&secret), + }) + .await + .unwrap(); + + secret + } + + fn hash_access_secret(secret: &str) -> String { + let digest = Sha256::digest(secret.as_bytes()); + URL_SAFE_NO_PAD.encode(digest) + } + async fn spawn_upstream_server() -> String { let app = Router::new().route("/crm/leads", post(create_lead)); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/apps/ui/html/api-keys.html b/apps/ui/html/api-keys.html index edf3069..53fa086 100644 --- a/apps/ui/html/api-keys.html +++ b/apps/ui/html/api-keys.html @@ -115,7 +115,7 @@
write
-
Create, update, and delete operations and their configurations.
+
Execute `tools/call` requests against published agent toolsets.
deploy
-
Publish agents and operations and perform deploy-scoped platform actions.
+
Reserved for deploy-scoped automation. Today it also permits MCP read/write flows.
diff --git a/apps/ui/js/api-keys.js b/apps/ui/js/api-keys.js index b1d3b9d..3b15c0f 100644 --- a/apps/ui/js/api-keys.js +++ b/apps/ui/js/api-keys.js @@ -5,9 +5,9 @@ var search = ''; var SCOPES = ['read', 'write', 'deploy']; var SCOPE_DESC = { - read: 'Read operations, logs, and usage', - write: 'Create and update operations', - deploy: 'Publish agents and operations', + read: 'Initialize MCP sessions and list tools', + write: 'Execute published tools through MCP', + deploy: 'Reserved for deploy-scoped automation', }; function mapKeyRecord(record) { diff --git a/crates/crank-registry/src/postgres.rs b/crates/crank-registry/src/postgres.rs index 9fc38a3..eec1525 100644 --- a/crates/crank-registry/src/postgres.rs +++ b/crates/crank-registry/src/postgres.rs @@ -584,6 +584,36 @@ impl PostgresRegistry { rows.iter().map(map_platform_api_key_record).collect() } + pub async fn get_platform_api_key_by_secret_for_workspace_slug( + &self, + workspace_slug: &str, + secret_hash: &str, + ) -> Result, RegistryError> { + let row = sqlx::query( + "select + k.id, + k.workspace_id, + k.name, + k.prefix, + k.scopes_json, + k.status, + to_char(k.created_at at time zone 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') as created_at, + to_char(k.last_used_at at time zone 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') as last_used_at + from platform_api_keys k + join workspaces w on w.id = k.workspace_id + where w.slug = $1 + and k.secret_hash = $2 + and k.status = 'active' + limit 1", + ) + .bind(workspace_slug) + .bind(secret_hash) + .fetch_optional(&self.pool) + .await?; + + row.as_ref().map(map_platform_api_key_record).transpose() + } + pub async fn create_platform_api_key( &self, request: CreatePlatformApiKeyRequest<'_>, @@ -680,6 +710,32 @@ impl PostgresRegistry { Ok(()) } + pub async fn touch_platform_api_key( + &self, + workspace_id: &WorkspaceId, + key_id: &PlatformApiKeyId, + used_at: &str, + ) -> Result<(), RegistryError> { + let result = sqlx::query( + "update platform_api_keys + set last_used_at = $3::timestamptz + where workspace_id = $1 and id = $2", + ) + .bind(workspace_id.as_str()) + .bind(key_id.as_str()) + .bind(used_at) + .execute(&self.pool) + .await?; + + if result.rows_affected() == 0 { + return Err(RegistryError::PlatformApiKeyNotFound { + key_id: key_id.as_str().to_owned(), + }); + } + + Ok(()) + } + pub async fn create_invocation_log( &self, request: CreateInvocationLogRequest<'_>, diff --git a/docs/admin-api.md b/docs/admin-api.md index 09d59c8..39cbb10 100644 --- a/docs/admin-api.md +++ b/docs/admin-api.md @@ -145,6 +145,7 @@ - `POST /platform-api-keys` возвращает metadata ключа и одноразовый `secret`; - `secret` доступен только в create-response; - list endpoints возвращают только metadata, `prefix`, `status`, `scopes` и `last_used_at`. +- `last_used_at` обновляется при успешной machine-auth аутентификации этим ключом в `mcp-server`. ### 5.8. Observability diff --git a/docs/alpine-ui-integration-plan.md b/docs/alpine-ui-integration-plan.md index 61e775c..5175493 100644 --- a/docs/alpine-ui-integration-plan.md +++ b/docs/alpine-ui-integration-plan.md @@ -201,7 +201,6 @@ UI-файлы: Что еще не хватает: -- отдельный usage/last-used update flow, когда ключи реально начнут использоваться в runtime; - если захотим richer UX, можно добавить server-side pagination и фильтрацию по статусу. Отдельный конфликт: @@ -213,7 +212,8 @@ UI-файлы: - страница уже сажается на текущий backend без новых ручек; - live `list/create/revoke/delete` можно считать закрытым; -- следующий реальный шаг здесь только в polishing вокруг usage и audit trail. +- `last_used_at` теперь обновляется через успешную machine-auth аутентификацию в `mcp-server`; +- следующий реальный шаг здесь только в polishing вокруг audit trail и richer filtering. ### 4.5. Logs diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index df5a872..0467e26 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -93,6 +93,19 @@ - конкретный curated toolset; - набор usage и log labels. +## 7.1. MCP authentication + +`mcp-server` использует workspace-scoped `platform API keys` как machine credentials. + +Контракт: + +- клиент передает `Authorization: Bearer crk_...`; +- ключ должен принадлежать workspace из path; +- `read` разрешает `initialize`, `notifications/initialized`, `ping`, `tools/list`; +- `write` разрешает `tools/call`; +- `deploy` сейчас включает те же MCP права, что и `write`, и зарезервирован для deploy-scoped automation; +- успешная аутентификация обновляет `platform_api_keys.last_used_at`. + ## 8. MCP lifecycle Поддерживаемые JSON-RPC методы: