Model Context Protocol (MCP)
MCP provides a standardized transport for connecting agents to external tools, resources, and prompts over stdio or streamable HTTP. ish-harness keeps JSON-RPC framing, protocol negotiation (2025-03-26), tool normalization, and structured schema validation in Rust while exposing language-native transport clients and server adapters in every SDK.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
import asyncio
from ish import Agent, OpenAICompatibleModel
from ish.integrations.protocols import load_mcp_tools
async def main() -> None:
async with await load_mcp_tools(command=["python3", "mcp_server.py"]) as tools:
agent = Agent(
name="mcp_user",
model=OpenAICompatibleModel(model="gpt-4o-mini"),
instructions="Use connected MCP tools when needed.",
tools=list(tools),
)
result = await agent.run("Add 40 and 2 using the MCP tool.")
print(result.content)
asyncio.run(main())
import { Agent, IshClient, McpTransportClient } from "ish-harness";
const client = new IshClient();
const mcp = McpTransportClient.stdio(client, ["python3", "mcp_server.py"]);
try {
const discovered = await mcp.listTools();
const bridgedTools = discovered.map((tool) => ({
name: String(tool.name),
description: String(tool.description ?? ""),
parameters: (tool.inputSchema ?? { type: "object" }) as Record<string, unknown>,
execute: (args: Record<string, unknown>) => mcp.callTool(String(tool.name), args),
}));
const agent = new Agent({
name: "mcp_user",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
tools: bridgedTools,
max_turns: 4,
});
const result = await agent.run("Add 40 and 2 using the MCP tool.");
console.log(result.content);
} finally {
mcp.close();
client.close();
}
use ish_harness::caps::mcp::transports::NativeMcpClient;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mcp = NativeMcpClient::start_stdio(
vec!["python3".into(), "mcp_server.py".into()],
None,
None,
30.0,
)
.await?;
let tools = mcp.list_tools().await?;
println!("Discovered {} MCP tool(s)", tools.len());
let output = mcp.call_tool("add", &json!({ "a": 40, "b": 2 })).await?;
println!("Tool output: {output}");
mcp.close().await;
Ok(())
}
package main
import (
"context"
"fmt"
ish "github.com/ish-harness/ish-harness/sdks/go"
)
func main() {
client, err := ish.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
mcp, err := ish.StartMcpStdioTransport(client, []string{"python3", "mcp_server.py"}, "", nil, 30.0)
if err != nil {
panic(err)
}
defer mcp.Close()
catalog, err := mcp.ListTools()
if err != nil {
panic(err)
}
var agentTools []ish.AgentTool
for _, item := range catalog {
name, _ := item["name"].(string)
desc, _ := item["description"].(string)
schema, _ := item["inputSchema"].(map[string]any)
agentTools = append(agentTools, ish.AgentTool{
Name: name,
Description: desc,
Parameters: schema,
Execute: func(ctx context.Context, args map[string]any) (any, error) {
return mcp.CallTool(name, args)
},
})
}
agent := ish.NewAgent(client, ish.AgentRunRequest{
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
Tools: agentTools,
MaxTurns: ish.IntPtr(4),
})
res, err := agent.Run(context.Background(), "Add 40 and 2 using the MCP tool.")
if err != nil {
panic(err)
}
fmt.Println(res["content"])
}
using System;
using System.Collections.Generic;
using Ish.Harness;
using var client = new IshClient();
using var mcp = McpTransportClient.Stdio(client, ["python3", "mcp_server.py"]);
var catalog = mcp.ListTools();
var agentTools = new List<AgentTool>();
foreach (var entry in catalog)
{
var toolName = entry.GetProperty("name").GetString()!;
var desc = entry.TryGetProperty("description", out var d) ? d.GetString() : null;
agentTools.Add(new AgentTool
{
Name = toolName,
Description = desc ?? toolName,
Parameters = entry.GetProperty("inputSchema").Clone(),
Execute = (args, _) => mcp.CallTool(toolName, args)
});
}
var result = client.Run(new AgentRunRequest
{
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
UserPrompt = "Add 40 and 2 using the MCP tool.",
Tools = agentTools,
MaxTurns = 4
});
Console.WriteLine(result.GetProperty("content").GetString());
import com.fasterxml.jackson.databind.JsonNode;
import io.github.ishharness.IshClient;
import io.github.ishharness.McpTransportClient;
import java.nio.file.Path;
import java.util.List;
public class McpClientExample {
public static void main(String[] args) {
try (var client = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")));
var mcp = McpTransportClient.stdio(client, List.of("python3", "mcp_server.py"))) {
var request =
new IshClient.AgentRequest(
"gpt-4o-mini",
"Use connected MCP tools when needed.",
"Add 40 and 2 using the MCP tool.")
.provider("openai_chat")
.maxTurns(4);
for (JsonNode entry : mcp.listTools()) {
String name = entry.path("name").asText();
String desc = entry.path("description").asText(name);
JsonNode schema = entry.path("inputSchema");
request.tool(name, desc, schema, arguments -> mcp.callTool(name, arguments));
}
JsonNode result = client.runAgent(request);
System.out.println(result.path("content").asText());
}
}
}
Load MCP tools into an agent
Connect to a local stdio or remote HTTP MCP server, discover its tool catalog, and wire those tools into an Agent run:
Read resources, retrieve prompts
Inspect and fetch server-hosted resources and reusable prompt templates over stdio or remote HTTP transports:
- Python
- TypeScript
- Rust
- Go
- C#
- Java
import asyncio
from ish.integrations.protocols import RemoteMCPClient
async def main() -> None:
async with RemoteMCPClient(
url="https://mcp.example.com/mcp",
headers={"Authorization": "Bearer token"},
) as client:
resources = await client.list_resources()
doc = await client.read_resource(resources[0]["uri"])
prompts = await client.list_prompts()
rendered = await client.get_prompt(prompts[0]["name"], {"topic": "sandboxes"})
print(doc, rendered)
asyncio.run(main())
import { IshClient, McpTransportClient } from "ish-harness";
const client = new IshClient();
const mcp = McpTransportClient.http(client, "https://mcp.example.com/mcp", {
headers: { Authorization: "Bearer token" },
});
try {
const resources = await mcp.listResources();
const doc = await mcp.readResource(String(resources[0].uri));
const prompts = await mcp.listPrompts();
const rendered = await mcp.getPrompt(String(prompts[0].name), { topic: "sandboxes" });
console.log(doc, rendered);
} finally {
mcp.close();
client.close();
}
use std::collections::HashMap;
use ish_harness::caps::mcp::transports::NativeMcpClient;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), "Bearer token".to_string());
let mcp = NativeMcpClient::start_http(
"https://mcp.example.com/mcp".to_string(),
Some(headers),
30.0,
)
.await?;
let resources = mcp.list_resources().await?;
if let Some(uri) = resources.first().and_then(|r| r.get("uri")).and_then(|u| u.as_str()) {
let doc = mcp.read_resource(uri).await?;
println!("Resource: {doc}");
}
let prompts = mcp.list_prompts().await?;
if let Some(name) = prompts.first().and_then(|p| p.get("name")).and_then(|n| n.as_str()) {
let rendered = mcp.get_prompt(name, Some(&json!({ "topic": "sandboxes" }))).await?;
println!("Prompt: {rendered}");
}
mcp.close().await;
Ok(())
}
package main
import (
"fmt"
ish "github.com/ish-harness/ish-harness/sdks/go"
)
func main() {
client, err := ish.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
mcp, err := ish.StartMcpHTTPTransport(
client,
"https://mcp.example.com/mcp",
map[string]string{"Authorization": "Bearer token"},
30.0,
)
if err != nil {
panic(err)
}
defer mcp.Close()
resources, _ := mcp.ListResources()
doc, _ := mcp.ReadResource(resources[0]["uri"].(string))
prompts, _ := mcp.ListPrompts()
rendered, _ := mcp.GetPrompt(prompts[0]["name"].(string), map[string]any{"topic": "sandboxes"})
fmt.Println(doc, rendered)
}
using System;
using System.Collections.Generic;
using Ish.Harness;
using var client = new IshClient();
using var mcp = McpTransportClient.Http(
client,
"https://mcp.example.com/mcp",
new Dictionary<string, string> { ["Authorization"] = "Bearer token" });
var resources = mcp.ListResources();
var doc = mcp.ReadResource(resources[0].GetProperty("uri").GetString()!);
var prompts = mcp.ListPrompts();
var rendered = mcp.GetPrompt(prompts[0].GetProperty("name").GetString()!, new { topic = "sandboxes" });
Console.WriteLine($"{doc}\n{rendered}");
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.ishharness.IshClient;
import io.github.ishharness.McpTransportClient;
import java.nio.file.Path;
import java.util.Map;
public class McpResourcesAndPromptsExample {
public static void main(String[] args) {
var mapper = new ObjectMapper();
try (var client = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")));
var mcp =
McpTransportClient.http(
client,
"https://mcp.example.com/mcp",
Map.of("Authorization", "Bearer token"),
30.0)) {
var resources = mcp.listResources();
JsonNode doc = mcp.readResource(resources.get(0).path("uri").asText());
var prompts = mcp.listPrompts();
JsonNode rendered =
mcp.getPrompt(
prompts.get(0).path("name").asText(),
mapper.createObjectNode().put("topic", "sandboxes"));
System.out.println(doc + "\n" + rendered);
}
}
}
Serve tools, resources, prompts
Expose custom tools, read-only resources, and prompt definitions over stdio (serve_stdio / runStdio) or embed request handling (handleRequest) inside your own server:
- Python
- TypeScript
- Rust
- Go
- C#
- Java
from ish import tool
from ish.integrations.protocols import (
MCPPromptDefinition,
MCPResourceDefinition,
MCPServer,
)
@tool
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
server = MCPServer(
tools=[add],
resources=[
MCPResourceDefinition(
uri="docs://guide",
name="guide",
description="Project guide",
mimeType="text/plain",
read=lambda _uri: "Use MCP tools and resources safely.",
)
],
prompts=[
MCPPromptDefinition(
name="review",
description="Review a topic",
arguments=[{"name": "topic", "required": True}],
handler=lambda topic: {
"messages": [{"role": "user", "content": {"type": "text", "text": f"Review {topic}"}}]
},
)
],
)
if __name__ == "__main__":
server.serve_stdio()
import { IshClient, McpServer } from "ish-harness";
const client = new IshClient();
const server = new McpServer(client, {
name: "example-mcp",
version: "1.0.0",
tools: [
{
name: "add",
description: "Add two integers",
inputSchema: {
type: "object",
properties: { a: { type: "integer" }, b: { type: "integer" } },
required: ["a", "b"],
},
handler: ({ a, b }) => Number(a) + Number(b),
},
],
resources: [
{
uri: "docs://guide",
name: "guide",
read: (uri) => ({ contents: [{ uri, text: "Use MCP tools and resources safely." }] }),
},
],
prompts: [
{
name: "review",
description: "Review a topic",
arguments: [{ name: "topic", required: true }],
handler: ({ topic }) => ({
messages: [{ role: "user", content: { type: "text", text: `Review ${topic}` } }],
}),
},
],
});
await server.runStdio();
client.close();
use ish_harness::mcp::{complete_tool_call, server_dispatch};
use serde_json::json;
fn main() {
let tools = vec![json!({
"name": "add",
"description": "Add two integers",
"inputSchema": {
"type": "object",
"properties": { "a": { "type": "integer" }, "b": { "type": "integer" } },
"required": ["a", "b"]
}
})];
let resources = vec![json!({ "uri": "docs://guide", "name": "guide", "mimeType": "text/plain" })];
let prompts = vec![json!({ "name": "review", "description": "Review a topic" })];
let list_req = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
let list_resp = server_dispatch(&list_req, "example-mcp", "1.0.0", &tools, &resources, &prompts, None);
println!("tools/list response: {list_resp}");
let call_resp = complete_tool_call(json!(2), "42", false, true, "example-mcp", "1.0.0");
println!("tools/call result: {call_resp}");
}
package main
import (
"context"
"fmt"
ish "github.com/ish-harness/ish-harness/sdks/go"
)
func main() {
client, err := ish.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
mcp := ish.NewMcpServer(
client,
"example-mcp",
"1.0.0",
nil,
[]ish.McpServerTool{
{
Name: "add",
Description: "Add two integers",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"a": map[string]any{"type": "integer"},
"b": map[string]any{"type": "integer"},
},
"required": []string{"a", "b"},
},
Handler: func(ctx context.Context, args map[string]any) (any, error) {
return int(args["a"].(float64)) + int(args["b"].(float64)), nil
},
},
},
[]ish.McpServerResource{
{
URI: "docs://guide",
Name: "guide",
MimeType: "text/plain",
Read: func(ctx context.Context, uri string) (any, error) {
return map[string]any{"contents": []map[string]any{{"uri": uri, "text": "Use MCP safely."}}}, nil
},
},
},
nil,
[]ish.McpServerPrompt{
{
Name: "review",
Description: "Review a topic",
Arguments: []map[string]any{{"name": "topic", "required": true}},
Handler: func(ctx context.Context, args map[string]any) (any, error) {
return map[string]any{
"messages": []map[string]any{
{"role": "user", "content": map[string]any{"type": "text", "text": fmt.Sprintf("Review %v", args["topic"])}},
},
}, nil
},
},
},
nil,
)
resp, err := mcp.HandleRequest(context.Background(), map[string]any{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": map[string]any{"name": "add", "arguments": map[string]any{"a": 40, "b": 2}},
})
if err != nil {
panic(err)
}
fmt.Println(resp)
}
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Ish.Harness;
using var client = new IshClient();
var schema = JsonDocument.Parse("""{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]}""").RootElement;
var server = new McpServer(
client,
tools:
[
new McpServerTool(
"add",
(args, _) => ValueTask.FromResult<object?>(
args.GetProperty("a").GetInt32() + args.GetProperty("b").GetInt32()),
"Add two integers",
schema)
],
resources:
[
new McpServerResource(
"docs://guide",
"guide",
(uri, _) => ValueTask.FromResult<object?>(new { contents = new[] { new { uri, text = "Use MCP safely." } } }))
],
prompts:
[
new McpServerPrompt(
"review",
(args, _) => ValueTask.FromResult<object?>(new
{
messages = new[]
{
new { role = "user", content = new { type = "text", text = $"Review {args.GetProperty("topic").GetString()}" } }
}
}))
]);
await server.RunStdioAsync();
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.ishharness.IshClient;
import io.github.ishharness.McpServer;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class McpServerExample {
public static void main(String[] args) throws Exception {
var mapper = new ObjectMapper();
var schema =
mapper.readTree(
"{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"integer\"},\"b\":{\"type\":\"integer\"}},\"required\":[\"a\",\"b\"]}");
try (var client = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")))) {
var server =
new McpServer(
client,
List.of(
new McpServer.Tool(
"add",
arguments ->
CompletableFuture.completedFuture(
mapper.valueToTree(
arguments.path("a").asInt() + arguments.path("b").asInt())),
"Add two integers",
schema,
null)),
List.of(
new McpServer.Resource(
"docs://guide",
"guide",
uri ->
CompletableFuture.completedFuture(
mapper.valueToTree(
Map.of("contents", List.of(Map.of("uri", uri, "text", "Use MCP safely."))))),
"Project guide",
"text/plain")),
List.of(),
List.of(
new McpServer.Prompt(
"review",
arguments ->
CompletableFuture.completedFuture(
mapper.valueToTree(
Map.of(
"messages",
List.of(
Map.of(
"role",
"user",
"content",
Map.of(
"type",
"text",
"text",
"Review " + arguments.path("topic").asText())))))),
List.of(mapper.readTree("{\"name\":\"topic\",\"required\":true}")),
"Review a topic")),
"example-mcp",
"1.0.0",
null,
null);
server.runStdio();
}
}
}