aKode: consegna delle sessioni al server memoria (memory_ingest_session)

- ext/memoria: trascrizione compatta e cumulativa del thread (utente, risposte
  finali senza commentary, comandi con output troncato a ~1500 caratteri,
  file modificati, ricerche web, altri server MCP; le chiamate al server
  memoria sono ignorate), limite di ~150k caratteri tenendo il primo
  messaggio e i turni più recenti, external_context (web, other_mcp).
- Consegna con reason "idle" dopo `[memoria] deliver_idle_minutes` minuti di
  inattività (predefinito 10, il timer si annulla a ogni nuovo turno) e con
  reason "end" alla chiusura del thread (al massimo 5 s, poi rinuncia).
  Solo se ci sono turni nuovi dall'ultima consegna accettata (queued,
  duplicate, skipped); `[memoria] deliver_sessions = false` la spegne. Solo
  thread dell'utente, con il plugin memoria attivo e il server pronto.
- akode-mcp: McpResourceClient::call_tool e McpConnectionSet::call_host_tool
  per le chiamate dell'host a strumenti non elencati e fuori dal filtro
  enabled_tools (il filtro resta per il modello).
- extension-api: on_thread_closing, chiamato a inizio chiusura quando i server
  MCP sono ancora connessi (on_thread_stop arriva dopo il loro arresto).
- Test sul modello di ext/memoria/src/tests.rs: ruoli, compattazione,
  esclusione del server memoria, external_context, nessuna consegna senza
  turni nuovi, errori, timer di inattività; test del percorso host in
  akode-mcp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-15 00:49:51 +01:00
parent 854c7a66c9
commit 6d4c830805
9 changed files with 1233 additions and 10 deletions

View File

@@ -1088,11 +1088,51 @@ impl McpConnectionSet {
tool: &str,
environment_id: Option<&str>,
arguments: Option<serde_json::Value>,
mut meta: Option<serde_json::Value>,
meta: Option<serde_json::Value>,
requested_timeout: Option<Duration>,
wait_for_server: bool,
) -> Result<CallToolResult> {
self.validate_tool_call(server, tool, environment_id)?;
self.call_validated_tool(server, tool, arguments, meta, requested_timeout, wait_for_server)
.await
}
/// Calls a tool on behalf of the host (an extension), never on behalf of the model.
///
/// Host calls may target tools the server does not list and tools outside the server's
/// `enabled_tools`/`disabled_tools` filter: that filter shapes what the model can see and
/// call, while host calls are fixed in code (for example the `memoria` session delivery).
/// The server must still exist; no entitlement metadata is attached.
pub async fn call_host_tool(
&self,
server: &str,
tool: &str,
arguments: Option<serde_json::Value>,
requested_timeout: Option<Duration>,
) -> Result<CallToolResult> {
if !self.servers.contains_key(server) {
bail!("unknown MCP server '{server}'");
}
self.call_validated_tool(
server,
tool,
arguments,
/*meta*/ None,
requested_timeout,
/*wait_for_server*/ true,
)
.await
}
async fn call_validated_tool(
&self,
server: &str,
tool: &str,
arguments: Option<serde_json::Value>,
mut meta: Option<serde_json::Value>,
requested_timeout: Option<Duration>,
wait_for_server: bool,
) -> Result<CallToolResult> {
let view = &self.servers[server];
let client = if wait_for_server {
view.connection

View File

@@ -5122,3 +5122,54 @@ async fn view_only_changes_reuse_connection_and_preserve_the_old_step() {
);
assert_eq!(new_call.tool_approval_mode(), AppToolApproval::Approve);
}
#[tokio::test]
async fn host_tool_calls_bypass_the_model_tool_filter_but_not_unknown_servers() {
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionSet::new_uninitialized(
&approval_policy,
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
manager.insert_test_client(
"memoria".to_string(),
create_ready_async_managed_client(vec![create_test_tool("memoria", "memory_recall")])
.await,
);
manager
.servers
.get_mut("memoria")
.expect("test server exists")
.tool_filter = ToolFilter {
enabled: Some(HashSet::from(["memory_recall".to_string()])),
disabled: HashSet::new(),
};
// The model path refuses tools outside the server's filter.
let error = manager
.validate_tool_call("memoria", "memory_ingest_session", /*environment_id*/ None)
.expect_err("filtered tool must be rejected for the model");
assert!(error.to_string().contains("disabled"), "{error}");
// The host path is not stopped by the filter (the fake transport then fails or stalls).
let host_call = tokio::time::timeout(
Duration::from_millis(500),
manager.call_host_tool(
"memoria",
"memory_ingest_session",
Some(serde_json::json!({})),
Some(Duration::from_millis(200)),
),
)
.await;
if let Ok(Err(error)) = host_call {
assert!(!error.to_string().contains("disabled"), "{error}");
}
let error = manager
.call_host_tool("other", "memory_ingest_session", None, None)
.await
.expect_err("unknown server");
assert!(error.to_string().contains("unknown MCP server"), "{error}");
}

View File

@@ -2,6 +2,7 @@ use std::sync::Arc;
use std::sync::Weak;
use std::time::Duration;
use akode_protocol::mcp::CallToolResult;
use akode_protocol::mcp::Resource;
use akode_protocol::mcp::ResourceContent;
use anyhow::Context;
@@ -153,6 +154,32 @@ impl McpResourceClient {
})
}
/// Calls a tool of the named server for the host (an extension), not for the model.
///
/// The tool may be unlisted and outside the server's tool filter (see
/// `McpConnectionSet::call_host_tool`). `timeout` bounds the call, including server startup.
pub async fn call_tool(
&self,
server: &str,
tool: &str,
arguments: serde_json::Value,
timeout: Duration,
) -> Result<CallToolResult> {
let connections = self.runtime.latest_connections();
match tokio::time::timeout(
timeout,
connections.call_host_tool(server, tool, Some(arguments), Some(timeout)),
)
.await
{
Ok(result) => result,
Err(_) => Err(anyhow::anyhow!(
"tool call `{server}/{tool}` timed out after {} ms",
timeout.as_millis()
)),
}
}
/// Reads one resource from the named server.
pub async fn read_resource(&self, server: &str, uri: &str) -> Result<McpResourceReadResult> {
let params = ReadResourceRequestParams::new(uri.to_string());