Skip to Content
DocsAgentsUsing MCP

Integrating MCP with Kastrax AI Agents ✅

Model Context Protocol (MCP) is a standardized protocol that enables AI agents to discover and interact with external tools, services, and knowledge bases. Kastrax provides robust support for MCP, allowing your agents to leverage a wide ecosystem of third-party capabilities without writing custom integrations.

MCP Architecture in Kastrax ✅

Kastrax implements MCP support through a layered architecture that provides flexibility and extensibility:

  1. MCP Client Layer: Manages connections to MCP servers and handles protocol-specific communication
  2. Tool Adapter Layer: Converts MCP tool definitions into Kastrax-compatible tool interfaces
  3. Agent Integration Layer: Enables agents to discover and use MCP tools seamlessly

This architecture supports multiple transport protocols:

  • Stdio: For local MCP servers running as child processes
  • HTTP/WebSocket: For remote MCP servers accessible over the network
  • Custom Transports: Extensible architecture for implementing additional protocols

Adding MCP Support to Your Project ✅

To use MCP with Kastrax, you need to include the MCP module in your project dependencies:

// In your build.gradle.kts file dependencies { implementation("ai.kastrax:kastrax-core:1.0.0") implementation("ai.kastrax:kastrax-mcp:1.0.0") // Add MCP support }

The kastrax-mcp module provides all the necessary components for integrating with MCP servers.

Configuring MCP Clients ✅

Kastrax provides a flexible MCPClient class that manages connections to multiple MCP servers. The client automatically selects the appropriate transport protocol based on your configuration:

  • Process-based servers: Uses Stdio transport for local processes
  • Network-based servers: Uses HTTP/WebSocket for remote servers

Here’s how to configure an MCP client in Kastrax:

import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.config.MCPServerConfig import ai.kastrax.mcp.config.ProcessConfig import ai.kastrax.mcp.config.HttpConfig // Create an MCP client with multiple server configurations val mcpClient = MCPClient( servers = mapOf( // Process-based MCP server (using Stdio transport) "sequential" to MCPServerConfig( process = ProcessConfig( command = "npx", args = listOf("-y", "@modelcontextprotocol/server-sequential-thinking"), environment = mapOf("NODE_ENV" to "production") ) ), // HTTP-based MCP server "weather" to MCPServerConfig( http = HttpConfig( url = "http://localhost:8080/mcp", headers = mapOf("Authorization" to "Bearer your-token") ) ) ) ) ## Integrating MCP Tools with Agents ✅ Kastrax provides two approaches for integrating MCP tools with your agents, each suited for different use cases: ### Static Tool Integration Use this approach when: - You have a single MCP connection - The tools are used by a single user/context - Tool configuration remains constant - You want to initialize an agent with a fixed set of tools ```kotlin import ai.kastrax.core.agent.Agent import ai.kastrax.core.agent.AgentConfig import ai.kastrax.core.llm.DeepSeekProvider import ai.kastrax.mcp.MCPClient // Create the MCP client val mcpClient = MCPClient(/* configuration */) // Get all available tools from the MCP servers val mcpTools = mcpClient.getTools() // Create an agent with the MCP tools val agent = Agent( config = AgentConfig( name = "CLI Assistant", description = "An assistant that helps with command-line tasks", instructions = "You help users with CLI tasks and provide accurate command suggestions.", llmProvider = DeepSeekProvider(apiKey = "your-deepseek-api-key"), tools = mcpTools // Tools are fixed at agent creation ) )

Dynamic Tool Integration

Use this approach when:

  • You need per-request tool configuration
  • Tools need different credentials per user
  • Running in a multi-user environment
  • Tool configuration needs to change dynamically
import ai.kastrax.core.agent.Agent import ai.kastrax.core.agent.AgentConfig import ai.kastrax.core.llm.DeepSeekProvider import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.config.MCPServerConfig import ai.kastrax.mcp.config.ProcessConfig // Create a configurable MCP client val mcpClient = MCPClient( servers = mapOf( "example" to MCPServerConfig( process = ProcessConfig( command = "npx", args = listOf("-y", "@example/fakemcp"), environment = mapOf("API_KEY" to "your-api-key") ) ) ) ) // Create the agent without MCP tools initially val agent = Agent( config = AgentConfig( name = "Dynamic Assistant", description = "An assistant that uses dynamically configured tools", instructions = "You help users with various tasks using the most appropriate tools.", llmProvider = DeepSeekProvider(apiKey = "your-deepseek-api-key") // No tools specified here - they'll be provided at runtime ) ) // Later, when handling a user request: fun handleUserRequest(userId: String, input: String) { // Get user-specific tool configuration val userApiKey = getUserApiKey(userId) // Configure MCP client with user-specific credentials mcpClient.updateServerEnvironment("example", mapOf("API_KEY" to userApiKey)) // Get the current toolsets configured for this user val toolsets = mcpClient.getToolsets() // Generate a response using the dynamically configured tools val response = agent.generate( input = input, sessionId = userId, conversationId = "dynamic-tools-session", toolsets = toolsets ) // Return the response to the user return response.text }

Kastrax can integrate with various MCP registries that provide curated collections of tools. Here are some popular registries and how to use them with Kastrax:

mcp.run Registry

mcp.run provides pre-authenticated, secure MCP servers that can be easily integrated with Kastrax:

import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.config.MCPServerConfig import ai.kastrax.mcp.config.HttpConfig // Create an MCP client with mcp.run configuration val mcpClient = MCPClient( servers = mapOf( "marketing" to MCPServerConfig( http = HttpConfig( url = System.getenv("MCP_RUN_SSE_URL") ?: "", // No additional headers needed as the URL contains authentication ) ) ) )

Important: Each SSE URL on mcp.run contains a unique signature that should be treated like a password. Store it securely in your environment variables or configuration system.

# In your application.conf or environment variables MCP_RUN_SSE_URL=https://www.mcp.run/api/mcp/sse?nonce=...

Composio.dev Registry

Composio.dev offers a registry of MCP servers for various services like Google Sheets, Gmail, and more:

import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.config.MCPServerConfig import ai.kastrax.mcp.config.HttpConfig // Create an MCP client with Composio.dev configurations val mcpClient = MCPClient( servers = mapOf( "googleSheets" to MCPServerConfig( http = HttpConfig( url = "https://mcp.composio.dev/googlesheets/[private-url-path]" ) ), "gmail" to MCPServerConfig( http = HttpConfig( url = "https://mcp.composio.dev/gmail/[private-url-path]" ) ) ) )

Composio tools include built-in authentication capabilities, allowing your agent to guide users through the authentication process during conversation.

Smithery.ai Registry

Smithery.ai provides a registry of MCP servers that can be used with Kastrax:

import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.config.MCPServerConfig import ai.kastrax.mcp.config.ProcessConfig // For Unix/Mac val mcpClient = MCPClient( servers = mapOf( "sequentialThinking" to MCPServerConfig( process = ProcessConfig( command = "npx", args = listOf( "-y", "@smithery/cli@latest", "run", "@smithery-ai/server-sequential-thinking", "--config", "{}" ) ) ) ) ) // For Windows val windowsMcpClient = MCPClient( servers = mapOf( "sequentialThinking" to MCPServerConfig( process = ProcessConfig( command = "cmd", args = listOf( "/c", "npx", "-y", "@smithery/cli@latest", "run", "@smithery-ai/server-sequential-thinking", "--config", "{}" ) ) ) ) )

Filtering MCP Tools ✅

Kastrax allows you to filter the tools provided by MCP servers before passing them to your agents. This is useful when you want to limit the tools available to an agent or when you need to customize the tool set for specific use cases.

Filtering Tools by Name

Suppose your MCP server exposes three tools: weather, stockPrice, and news, but you want to exclude the news tool:

import ai.kastrax.mcp.MCPClient import ai.kastrax.core.agent.Agent import ai.kastrax.core.agent.AgentConfig import ai.kastrax.core.llm.DeepSeekProvider import ai.kastrax.core.tool.Tool // Create the MCP client val mcpClient = MCPClient(/* configuration */) // Get all tools from the MCP server val allTools = mcpClient.getTools() // Filter out the 'news' tool (tool names are namespaced as 'serverName_toolName') val filteredTools = allTools.filterNot { (name, _) -> name == "myServer_news" } // Create an agent with only the filtered tools val agent = Agent( config = AgentConfig( name = "Selective Agent", description = "An assistant with access to selected tools only", instructions = "You can access only weather and stock price information.", llmProvider = DeepSeekProvider(apiKey = "your-deepseek-api-key"), tools = filteredTools ) )

Selecting Specific Tools

Alternatively, you can select only the specific tools you want to use:

// Get all tools from the MCP server val allTools = mcpClient.getTools() // Select only the weather and stock price tools val selectedTools = allTools.filter { (name, _) -> name == "myServer_weather" || name == "myServer_stockPrice" } // Create an agent with only the selected tools val agent = Agent( config = AgentConfig( name = "Selective Agent", description = "An assistant with access to selected tools only", instructions = "You can access only weather and stock price information.", llmProvider = DeepSeekProvider(apiKey = "your-deepseek-api-key"), tools = selectedTools ) )

Advanced MCP Features ✅

Tool Transformation

Kastrax allows you to transform MCP tools before using them with your agents. This is useful for adding custom behavior, logging, or modifying tool parameters:

import ai.kastrax.mcp.MCPClient import ai.kastrax.mcp.MCPTool import ai.kastrax.core.tool.Tool // Create a wrapper that adds logging to MCP tools fun <I : Any, O : Any> addLoggingToTool(tool: Tool<I, O>): Tool<I, O> { return object : Tool<I, O> by tool { override suspend fun execute(input: I, context: ToolContext): ToolResult<O> { println("Executing tool: ${tool.definition.name} with input: $input") val startTime = System.currentTimeMillis() val result = tool.execute(input, context) val duration = System.currentTimeMillis() - startTime println("Tool execution completed in ${duration}ms with result: $result") return result } } } // Get MCP tools and transform them val mcpTools = mcpClient.getTools() val enhancedTools = mcpTools.mapValues { (_, tool) -> addLoggingToTool(tool) }

Custom MCP Server Implementation

Kastrax supports implementing your own MCP servers that can be used by your agents or shared with others:

import ai.kastrax.mcp.server.MCPServer import ai.kastrax.mcp.server.MCPToolDefinition class CustomMCPServer : MCPServer { override val serverInfo = MCPServerInfo( name = "custom-server", version = "1.0.0", description = "A custom MCP server with specialized tools" ) override val tools = listOf( MCPToolDefinition( name = "custom_tool", description = "A specialized tool for custom operations", parameters = /* parameter schema */, execute = { params -> // Tool implementation } ) ) }

Using the Kastrax Documentation Server ✅

Kastrax provides an MCP documentation server that can be used in your IDE to access comprehensive documentation about Kastrax features and capabilities. Check out our MCP Documentation Server guide to get started.

Next Steps ✅

Last updated on