You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by pi...@apache.org on 2025/07/16 18:57:48 UTC

(iggy) branch mcp updated: messages mcp

This is an automated email from the ASF dual-hosted git repository.

piotr pushed a commit to branch mcp
in repository https://gitbox.apache.org/repos/asf/iggy.git


The following commit(s) were added to refs/heads/mcp by this push:
     new c4e85ba8 messages mcp
c4e85ba8 is described below

commit c4e85ba861bd22af829b1fc3ee77bace1a600c92
Author: spetz <pi...@gmail.com>
AuthorDate: Wed Jul 16 20:57:42 2025 +0200

    messages mcp
---
 core/ai/mcp/config.toml             |   1 +
 core/ai/mcp/src/configs.rs          |   1 +
 core/ai/mcp/src/error.rs            |   2 +
 core/ai/mcp/src/main.rs             |  18 ++-
 core/ai/mcp/src/service/mod.rs      | 271 +++++++++++++++++++++++++++++++++---
 core/ai/mcp/src/service/requests.rs | 150 ++++++++++++++++++++
 core/ai/mcp/src/stream.rs           |  25 +---
 7 files changed, 426 insertions(+), 42 deletions(-)

diff --git a/core/ai/mcp/config.toml b/core/ai/mcp/config.toml
index 7bd59fd0..0078405e 100644
--- a/core/ai/mcp/config.toml
+++ b/core/ai/mcp/config.toml
@@ -31,6 +31,7 @@ address = "localhost:8090"
 username = "iggy"
 password = "iggy"
 # token = "secret" # Personal Access Token (PAT) can be used instead of username and password
+# consumer_name = "iggy-mcp" # Optional consumer name
 
 [permissions]
 create = true
diff --git a/core/ai/mcp/src/configs.rs b/core/ai/mcp/src/configs.rs
index 85957b94..4d86836d 100644
--- a/core/ai/mcp/src/configs.rs
+++ b/core/ai/mcp/src/configs.rs
@@ -33,6 +33,7 @@ pub struct IggyConfig {
     pub username: Option<String>,
     pub password: Option<String>,
     pub token: Option<String>,
+    pub consumer_name: Option<String>,
 }
 
 #[derive(Debug, Clone, Deserialize, Serialize)]
diff --git a/core/ai/mcp/src/error.rs b/core/ai/mcp/src/error.rs
index b722e575..d4e99e91 100644
--- a/core/ai/mcp/src/error.rs
+++ b/core/ai/mcp/src/error.rs
@@ -32,4 +32,6 @@ pub enum McpRuntimeError {
     IggyError(#[from] iggy::prelude::IggyError),
     #[error("Missing Iggy credentials")]
     MissingIggyCredentials,
+    #[error("Failed to create Iggy consumer ID")]
+    FailedToCreateConsumerId,
 }
diff --git a/core/ai/mcp/src/main.rs b/core/ai/mcp/src/main.rs
index 7eeb4342..3d5b236b 100644
--- a/core/ai/mcp/src/main.rs
+++ b/core/ai/mcp/src/main.rs
@@ -21,6 +21,7 @@ use configs::{McpServerConfig, McpTransport};
 use dotenvy::dotenv;
 use error::McpRuntimeError;
 use figlet_rs::FIGfont;
+use iggy::prelude::Identifier;
 use rmcp::{
     ServiceExt,
     model::ErrorData,
@@ -85,9 +86,14 @@ async fn main() -> Result<(), McpRuntimeError> {
 
     info!("Starting Iggy MCP Server, transport: {transport}...");
 
-    let iggy_clients = stream::init(config.iggy).await?;
-    let consumer = Arc::new(iggy_clients.consumer);
-    let producer = Arc::new(iggy_clients.producer);
+    let consumer_id =
+        Identifier::from_str_value(config.iggy.consumer_name.as_deref().unwrap_or("iggy-mcp"))
+            .map_err(|error| {
+                error!("Failed to create Iggy consumer ID: {:?}", error);
+                McpRuntimeError::FailedToCreateConsumerId
+            })?;
+    let iggy_consumer = Arc::new(iggy::prelude::Consumer::new(consumer_id));
+    let iggy_client = Arc::new(stream::init(config.iggy).await?);
     let permissions = Permissions {
         create: config.permissions.create,
         read: config.permissions.read,
@@ -96,7 +102,7 @@ async fn main() -> Result<(), McpRuntimeError> {
     };
 
     if transport == McpTransport::Stdio {
-        let Ok(service) = IggyService::new(consumer, producer, permissions)
+        let Ok(service) = IggyService::new(iggy_client, iggy_consumer, permissions)
             .serve(stdio())
             .await
             .inspect_err(|e| {
@@ -119,8 +125,8 @@ async fn main() -> Result<(), McpRuntimeError> {
         let service = StreamableHttpService::new(
             move || {
                 Ok(IggyService::new(
-                    consumer.clone(),
-                    producer.clone(),
+                    iggy_client.clone(),
+                    iggy_consumer.clone(),
                     permissions,
                 ))
             },
diff --git a/core/ai/mcp/src/service/mod.rs b/core/ai/mcp/src/service/mod.rs
index 71291595..b61ac1fd 100644
--- a/core/ai/mcp/src/service/mod.rs
+++ b/core/ai/mcp/src/service/mod.rs
@@ -16,9 +16,10 @@
  * under the License.
  */
 
-use std::sync::Arc;
-
-use iggy::prelude::{Identifier, IggyClient, IggyError, StreamClient};
+use iggy::prelude::{
+    Consumer, Identifier, IggyClient, IggyError, IggyTimestamp, MessageClient, PartitionClient,
+    PollingKind, PollingStrategy, SegmentClient, StreamClient, TopicClient,
+};
 use requests::*;
 use rmcp::{
     ServerHandler,
@@ -27,6 +28,7 @@ use rmcp::{
     tool, tool_handler, tool_router,
 };
 use serde::Serialize;
+use std::sync::Arc;
 use tracing::error;
 
 use crate::Permissions;
@@ -35,22 +37,18 @@ mod requests;
 #[derive(Debug, Clone)]
 pub struct IggyService {
     tool_router: ToolRouter<Self>,
-    consumer: Arc<IggyClient>,
-    _producer: Arc<IggyClient>,
+    client: Arc<IggyClient>,
+    consumer: Arc<Consumer>,
     permissions: Permissions,
 }
 
 #[tool_router]
 impl IggyService {
-    pub fn new(
-        consumer: Arc<IggyClient>,
-        producer: Arc<IggyClient>,
-        permissions: Permissions,
-    ) -> Self {
+    pub fn new(client: Arc<IggyClient>, consumer: Arc<Consumer>, permissions: Permissions) -> Self {
         Self {
             tool_router: Self::tool_router(),
+            client,
             consumer,
-            _producer: producer,
             permissions,
         }
     }
@@ -61,13 +59,13 @@ impl IggyService {
         Parameters(GetStream { stream_id }): Parameters<GetStream>,
     ) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_read()?;
-        request(self.consumer.get_stream(&id(&stream_id)?).await)
+        request(self.client.get_stream(&id(&stream_id)?).await)
     }
 
     #[tool(description = "Get streams")]
     pub async fn get_streams(&self) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_read()?;
-        request(self.consumer.get_streams().await)
+        request(self.client.get_streams().await)
     }
 
     #[tool(description = "Create stream")]
@@ -76,7 +74,7 @@ impl IggyService {
         Parameters(CreateStream { name, stream_id }): Parameters<CreateStream>,
     ) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_create()?;
-        request(self.consumer.create_stream(&name, stream_id).await)
+        request(self.client.create_stream(&name, stream_id).await)
     }
 
     #[tool(description = "Update stream")]
@@ -85,7 +83,7 @@ impl IggyService {
         Parameters(UpdateStream { stream_id, name }): Parameters<UpdateStream>,
     ) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_update()?;
-        request(self.consumer.update_stream(&id(&stream_id)?, &name).await)
+        request(self.client.update_stream(&id(&stream_id)?, &name).await)
     }
 
     #[tool(description = "Delete stream")]
@@ -94,7 +92,7 @@ impl IggyService {
         Parameters(DeleteStream { stream_id }): Parameters<DeleteStream>,
     ) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_delete()?;
-        request(self.consumer.delete_stream(&id(&stream_id)?).await)
+        request(self.client.delete_stream(&id(&stream_id)?).await)
     }
 
     #[tool(description = "Purge stream")]
@@ -103,7 +101,246 @@ impl IggyService {
         Parameters(PurgeStream { stream_id }): Parameters<PurgeStream>,
     ) -> Result<CallToolResult, ErrorData> {
         self.permissions.ensure_delete()?;
-        request(self.consumer.purge_stream(&id(&stream_id)?).await)
+        request(self.client.purge_stream(&id(&stream_id)?).await)
+    }
+
+    #[tool(description = "Get topics")]
+    pub async fn get_topics(
+        &self,
+        Parameters(GetTopics { stream_id }): Parameters<GetTopics>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_read()?;
+        request(self.client.get_topics(&id(&stream_id)?).await)
+    }
+
+    #[tool(description = "Get topic")]
+    pub async fn get_topic(
+        &self,
+        Parameters(GetTopic {
+            stream_id,
+            topic_id,
+        }): Parameters<GetTopic>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_read()?;
+        request(
+            self.client
+                .get_topic(&id(&stream_id)?, &id(&topic_id)?)
+                .await,
+        )
+    }
+
+    #[tool(description = "Create topic")]
+    pub async fn create_topic(
+        &self,
+        Parameters(CreateTopic {
+            stream_id,
+            name,
+            partitions_count,
+            compression_algorithm,
+            replication_factor,
+            topic_id,
+            message_expiry,
+            max_size,
+        }): Parameters<CreateTopic>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_create()?;
+        let compression_algorithm = compression_algorithm
+            .and_then(|ca| ca.parse().ok())
+            .unwrap_or_default();
+        let message_expiry = message_expiry
+            .and_then(|me| me.parse().ok())
+            .unwrap_or_default();
+        let max_size = max_size.and_then(|ms| ms.parse().ok()).unwrap_or_default();
+        request(
+            self.client
+                .create_topic(
+                    &id(&stream_id)?,
+                    &name,
+                    partitions_count,
+                    compression_algorithm,
+                    replication_factor,
+                    topic_id,
+                    message_expiry,
+                    max_size,
+                )
+                .await,
+        )
+    }
+
+    #[tool(description = "Update topic")]
+    pub async fn update_topic(
+        &self,
+        Parameters(UpdateTopic {
+            stream_id,
+            topic_id,
+            name,
+            compression_algorithm,
+            replication_factor,
+            message_expiry,
+            max_size,
+        }): Parameters<UpdateTopic>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_update()?;
+        let compression_algorithm = compression_algorithm
+            .and_then(|ca| ca.parse().ok())
+            .unwrap_or_default();
+        let message_expiry = message_expiry
+            .and_then(|me| me.parse().ok())
+            .unwrap_or_default();
+        let max_size = max_size.and_then(|ms| ms.parse().ok()).unwrap_or_default();
+        request(
+            self.client
+                .update_topic(
+                    &id(&stream_id)?,
+                    &id(&topic_id)?,
+                    &name,
+                    compression_algorithm,
+                    replication_factor,
+                    message_expiry,
+                    max_size,
+                )
+                .await,
+        )
+    }
+
+    #[tool(description = "Delete topic")]
+    pub async fn delete_topic(
+        &self,
+        Parameters(DeleteTopic {
+            stream_id,
+            topic_id,
+        }): Parameters<DeleteTopic>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_delete()?;
+        request(
+            self.client
+                .delete_topic(&id(&stream_id)?, &id(&topic_id)?)
+                .await,
+        )
+    }
+
+    #[tool(description = "Purge topic")]
+    pub async fn purge_topic(
+        &self,
+        Parameters(PurgeTopic {
+            stream_id,
+            topic_id,
+        }): Parameters<PurgeTopic>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_delete()?;
+        request(
+            self.client
+                .purge_topic(&id(&stream_id)?, &id(&topic_id)?)
+                .await,
+        )
+    }
+
+    #[tool(description = "Create partitions")]
+    pub async fn create_partitions(
+        &self,
+        Parameters(CreatePartitions {
+            stream_id,
+            topic_id,
+            partitions_count,
+        }): Parameters<CreatePartitions>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_create()?;
+        request(
+            self.client
+                .create_partitions(&id(&stream_id)?, &id(&topic_id)?, partitions_count)
+                .await,
+        )
+    }
+
+    #[tool(description = "Delete partitions")]
+    pub async fn delete_partitions(
+        &self,
+        Parameters(DeletePartitions {
+            stream_id,
+            topic_id,
+            partitions_count,
+        }): Parameters<DeletePartitions>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_delete()?;
+        request(
+            self.client
+                .delete_partitions(&id(&stream_id)?, &id(&topic_id)?, partitions_count)
+                .await,
+        )
+    }
+
+    #[tool(description = "Delete segments")]
+    pub async fn delete_segments(
+        &self,
+        Parameters(DeleteSegments {
+            stream_id,
+            topic_id,
+            partition_id,
+            segments_count,
+        }): Parameters<DeleteSegments>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_delete()?;
+        request(
+            self.client
+                .delete_segments(
+                    &id(&stream_id)?,
+                    &id(&topic_id)?,
+                    partition_id,
+                    segments_count,
+                )
+                .await,
+        )
+    }
+
+    #[tool(description = "Poll messages")]
+    pub async fn poll_messages(
+        &self,
+        Parameters(PollMessages {
+            stream_id,
+            topic_id,
+            partition_id,
+            strategy,
+            offset,
+            timestamp,
+            count,
+            auto_commit,
+        }): Parameters<PollMessages>,
+    ) -> Result<CallToolResult, ErrorData> {
+        self.permissions.ensure_read()?;
+        let offset = offset.unwrap_or(0);
+        let count = count.unwrap_or(10);
+        let mut auto_commit = auto_commit.unwrap_or(false);
+        let strategy = if let Some(strategy) = strategy {
+            match strategy.as_str() {
+                "offset" => PollingStrategy::offset(offset),
+                "first" => PollingStrategy::first(),
+                "last" => PollingStrategy::last(),
+                "next" => PollingStrategy::next(),
+                "timestamp" => PollingStrategy::timestamp(IggyTimestamp::from(
+                    timestamp.unwrap_or(IggyTimestamp::now().as_micros()),
+                )),
+                _ => PollingStrategy::offset(offset),
+            }
+        } else {
+            PollingStrategy::offset(offset)
+        };
+        if strategy.kind == PollingKind::Next {
+            auto_commit = true;
+        }
+
+        request(
+            self.client
+                .poll_messages(
+                    &id(&stream_id)?,
+                    &id(&topic_id)?,
+                    partition_id,
+                    &self.consumer,
+                    &strategy,
+                    count,
+                    auto_commit,
+                )
+                .await,
+        )
     }
 }
 
diff --git a/core/ai/mcp/src/service/requests.rs b/core/ai/mcp/src/service/requests.rs
index 5bbb5493..033440ae 100644
--- a/core/ai/mcp/src/service/requests.rs
+++ b/core/ai/mcp/src/service/requests.rs
@@ -52,3 +52,153 @@ pub struct PurgeStream {
     #[schemars(description = "stream identifier (name or number)")]
     pub stream_id: String,
 }
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct GetTopics {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct GetTopic {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct CreateTopic {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "name (required, must be unique)")]
+    pub name: String,
+
+    #[schemars(description = "partitions count (required, must be greater than 0)")]
+    pub partitions_count: u32,
+
+    #[schemars(description = "compression algorithm (optional, can be one of 'none', 'gzip')")]
+    pub compression_algorithm: Option<String>,
+
+    #[schemars(description = "replication factor (optional, must be greater than 0)")]
+    pub replication_factor: Option<u8>,
+
+    #[schemars(description = "topic identifier (numeric, optional)")]
+    pub topic_id: Option<u32>,
+
+    #[schemars(description = "message expiry (optional)")]
+    pub message_expiry: Option<String>,
+
+    #[schemars(description = "maximum size (optional)")]
+    pub max_size: Option<String>,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct UpdateTopic {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+
+    #[schemars(description = "name (required, must be unique)")]
+    pub name: String,
+
+    #[schemars(description = "compression algorithm (optional, can be one of 'none', 'gzip')")]
+    pub compression_algorithm: Option<String>,
+
+    #[schemars(description = "replication factor (optional, must be greater than 0)")]
+    pub replication_factor: Option<u8>,
+
+    #[schemars(description = "message expiry (optional)")]
+    pub message_expiry: Option<String>,
+
+    #[schemars(description = "maximum size (optional)")]
+    pub max_size: Option<String>,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct DeleteTopic {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct PurgeTopic {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct CreatePartitions {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+
+    #[schemars(description = "partitions count (required, must be greater than 0)")]
+    pub partitions_count: u32,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct DeletePartitions {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+
+    #[schemars(description = "partitions count (required, must be greater than 0)")]
+    pub partitions_count: u32,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct DeleteSegments {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+
+    #[schemars(description = "partition identifier (number)")]
+    pub partition_id: u32,
+
+    #[schemars(description = "segments count (required, must be greater than 0)")]
+    pub segments_count: u32,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct PollMessages {
+    #[schemars(description = "stream identifier (name or number)")]
+    pub stream_id: String,
+
+    #[schemars(description = "topic identifier (name or number)")]
+    pub topic_id: String,
+
+    #[schemars(description = "partition identifier (optional, number)")]
+    pub partition_id: Option<u32>,
+
+    #[schemars(description = "strategy (optional, string)")]
+    pub strategy: Option<String>,
+
+    #[schemars(description = "offset to start from (optional)")]
+    pub offset: Option<u64>,
+
+    #[schemars(description = "timestamp to start from (optional, microseconds from Unix Epoch)")]
+    pub timestamp: Option<u64>,
+
+    #[schemars(description = "count (optional, must be greater than 0)")]
+    pub count: Option<u32>,
+
+    #[schemars(description = "auto commit (optional, boolean)")]
+    pub auto_commit: Option<bool>,
+}
diff --git a/core/ai/mcp/src/stream.rs b/core/ai/mcp/src/stream.rs
index 969f3391..da47faeb 100644
--- a/core/ai/mcp/src/stream.rs
+++ b/core/ai/mcp/src/stream.rs
@@ -15,28 +15,15 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use crate::{configs::IggyConfig, error::McpRuntimeError};
 use iggy::prelude::{Client, IggyClient, IggyClientBuilder};
 use tracing::{error, info};
 
-use crate::{configs::IggyConfig, error::McpRuntimeError};
-
-pub struct IggyClients {
-    pub producer: IggyClient,
-    pub consumer: IggyClient,
-}
-
-pub async fn init(config: IggyConfig) -> Result<IggyClients, McpRuntimeError> {
-    let consumer = create_client(&config).await?;
-    let producer = create_client(&config).await?;
-    let iggy_clients = IggyClients { producer, consumer };
-    Ok(iggy_clients)
-}
-
-async fn create_client(config: &IggyConfig) -> Result<IggyClient, McpRuntimeError> {
-    let address = config.address.to_owned();
-    let username = config.username.to_owned();
-    let password = config.password.to_owned();
-    let token = config.token.to_owned();
+pub async fn init(config: IggyConfig) -> Result<IggyClient, McpRuntimeError> {
+    let address = config.address;
+    let username = config.username;
+    let password = config.password;
+    let token = config.token;
 
     let connection_string = if let Some(token) = token {
         if token.is_empty() {