Files
imeai-aKode/akode-rs/akode-mcp/src/resource_client.rs
andrea.difonzo 7c1c6dfa8d Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 12:37:52 +01:00

174 lines
5.8 KiB
Rust

use std::sync::Arc;
use std::sync::Weak;
use anyhow::Context;
use anyhow::Result;
use akode_protocol::mcp::Resource;
use akode_protocol::mcp::ResourceContent;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use crate::McpRuntime;
use crate::connection_manager::McpConnectionSet;
use crate::connection_manager::McpServerConnection;
/// One page of resources returned by an MCP server.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourcePage {
/// Resources advertised on this page.
pub resources: Vec<Resource>,
/// Opaque cursor to supply when requesting the next page.
pub next_cursor: Option<String>,
}
/// Contents returned after reading one MCP resource.
#[derive(Clone, Debug, PartialEq)]
pub struct McpResourceReadResult {
/// Text or blob content returned for the requested resource.
pub contents: Vec<ResourceContent>,
}
/// Access to MCP resources through the latest runtime.
#[derive(Clone)]
pub struct McpResourceClient {
runtime: Arc<McpRuntime>,
}
/// Opaque identity for the connection set currently used by an MCP resource client.
#[derive(Clone)]
pub struct McpResourceClientCacheKey(Weak<McpConnectionSet>);
impl PartialEq for McpResourceClientCacheKey {
fn eq(&self, other: &Self) -> bool {
self.0.ptr_eq(&other.0)
}
}
impl Eq for McpResourceClientCacheKey {}
/// Identity of one server's resource cache across MCP runtime publications.
///
/// Survives publications that reuse the same connection until resource caches are explicitly
/// invalidated. The key does not keep superseded connections alive.
#[derive(Clone)]
pub struct McpResourceServerCacheKey {
pub(crate) connection: Weak<McpServerConnection>,
pub(crate) generation: u64,
}
impl PartialEq for McpResourceServerCacheKey {
fn eq(&self, other: &Self) -> bool {
self.connection.ptr_eq(&other.connection) && self.generation == other.generation
}
}
impl Eq for McpResourceServerCacheKey {}
/// Opaque auth scope and server availability, independent of connection-set rebuilds.
/// This is for fixed, host-owned sources; it does not fingerprint arbitrary server config.
#[derive(Clone)]
pub struct McpResourceClientAuthKey {
pub(crate) generation: Arc<()>,
pub(crate) server: String,
pub(crate) available: bool,
}
impl PartialEq for McpResourceClientAuthKey {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.generation, &other.generation)
&& self.server == other.server
&& self.available == other.available
}
}
impl Eq for McpResourceClientAuthKey {}
impl std::fmt::Debug for McpResourceClient {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("McpResourceClient")
.finish_non_exhaustive()
}
}
impl McpResourceClient {
/// Creates a resource client that follows the thread's latest published runtime.
pub fn new(runtime: Arc<McpRuntime>) -> Self {
Self { runtime }
}
/// Returns the identity of the connection set used by this client.
pub fn cache_key(&self) -> McpResourceClientCacheKey {
McpResourceClientCacheKey(Arc::downgrade(&self.runtime.latest_connections()))
}
/// Returns a server's resource cache identity without starting its connection.
pub fn server_cache_key(&self, server: &str) -> Option<McpResourceServerCacheKey> {
self.runtime.resource_cache_key(server)
}
/// Tracks published auth and source availability without invalidating on unrelated
/// environment changes. This key contains no credentials.
pub fn auth_cache_key_for_server(&self, server: &str) -> McpResourceClientAuthKey {
self.runtime.auth_cache_key_for_server(server)
}
/// Returns whether this client can address the named server.
///
/// This does not wait for server startup.
pub async fn has_server(&self, server: &str) -> bool {
self.runtime.latest_connections().contains_server(server)
}
/// Lists one resource page from the named server.
pub async fn list_resources(
&self,
server: &str,
cursor: Option<String>,
) -> Result<McpResourcePage> {
let params =
cursor.map(|cursor| PaginatedRequestParams::default().with_cursor(Some(cursor)));
let result = self
.runtime
.latest_connections()
.list_resources(server, params)
.await?;
let resources = result
.resources
.into_iter()
.map(resource_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourcePage {
resources,
next_cursor: result.next_cursor,
})
}
/// 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());
let result = self
.runtime
.latest_connections()
.read_resource(server, params)
.await?;
let contents = result
.contents
.into_iter()
.map(resource_content_from_rmcp)
.collect::<Result<Vec<_>>>()?;
Ok(McpResourceReadResult { contents })
}
}
fn resource_from_rmcp(resource: rmcp::model::Resource) -> Result<Resource> {
let value = serde_json::to_value(resource).context("failed to serialize MCP resource")?;
Resource::from_mcp_value(value).context("failed to convert MCP resource")
}
fn resource_content_from_rmcp(content: rmcp::model::ResourceContents) -> Result<ResourceContent> {
let value =
serde_json::to_value(content).context("failed to serialize MCP resource content")?;
serde_json::from_value(value).context("failed to convert MCP resource content")
}