> For the complete documentation index, see [llms.txt](https://nuvex-ai.gitbook.io/nuvex-ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nuvex-ai.gitbook.io/nuvex-ai/developer-guide/mcp-documentation.md).

# MCP Documentation

#### **What is MCP**

MCP (Model Context Protocol) is an open standard for building secure bi-directional connections, allowing AI models to interact with data sources. Through MCP, developers can:

* Expose their data to AI models via MCP servers
* Build AI applications (MCP clients) that connect to these servers
* Enable AI models to maintain context across different tools and datasets

MCP addresses the challenges of AI systems accessing data, replacing traditional fragmented integration approaches with a universal open standard.

***

#### **MCP Implementation in Nuvex**

Nuvex implements complete MCP server functionality, allowing users to package their tools and data as MCP services for AI models to use. In Nuvex, MCP services are divided into two types:

* **Built-in MCP services**: System-predefined services such as `coin-api`
* **MCP Tool Importing**: Support for importing tools from external MCP services into the Nuvex tool marketplace, enabling easy integration of third-party capabilities
* **Dynamic MCP services**: Custom MCP services created by users through the API

***

#### **Core Components**

Nuvex’s MCP implementation contains the following core components:

* **MCP Server**: Provides the ability to interact with AI models through SSE (Server-Sent Events)
* **MCP Tools**: Functional units encapsulated in the MCP server, typically representing API calls
* **MCP Prompt Templates**: Prompt templates that help AI better use MCP tools
* **MCP Resources**: Static content that MCP services can access

***

#### **MCP Server Architecture**

Nuvex’s MCP implementation uses SSE as the transport layer, based on the following architecture:

* AI model/client initiates SSE connection to the MCP server endpoint
* Client can request tool lists, call tools, get prompts, access resources, etc.
* MCP server processes requests and returns responses via SSE stream
* All interactions use standardized MCP formats

***

#### **Token Authentication**

Nuvex uses API Token authentication for accessing all MCP-related APIs. This method is simple to implement and suitable for both development and production environments.

For detailed information on authentication methods, obtaining and using API Tokens, please refer to the Nuvex API Documentation.

```python
import requests

# Use API Token to call interfaces
headers = {"X-API-Token": "tk_your_api_token"}  # Replace with your API Token from the Nuvex platform

# Example: Create an MCP service
response = requests.post(
    "https://api.nuvex.ai/api/mcp/create",
    headers=headers,
    json={
        "mcp_name": "my-service",
        "tool_ids": ["00000000-0000-0000-0000-000000000001"],
        "description": "My MCP Service"
    }
)

print(response.json())
```

***

#### **Prerequisites**

* Registered Nuvex account and obtained API token
* Created or accessed certain tools (via the `/api/tools` endpoint)

***

#### **Importing MCP Service Tools**

Nuvex provides API interfaces that allow users to import tools from existing MCP services. This makes it easy to integrate functionality from third-party MCP services into your own Nuvex tool set for use in custom AI applications.

***

#### **Process for Importing MCP Tools**

* **Parse MCP service URL**: Use the `/api/tools/parse-mcp` interface to analyze an MCP service and obtain its tool definitions
* **Batch create tools**: Use the `/api/tools/create-batch` interface to batch import the parsed tools into your account

***

#### **Example: Parsing MCP Services**

The following example shows how to parse an existing MCP service and get its tool definitions:

```python
import requests

# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Parse MCP service URL
response = requests.post(
    "https://api.nuvex.ai/api/tools/parse-mcp",
    headers=headers,
    json={"mcp_url": "https://api.nuvex.ai/mcp/weather-service"}
)

# Get parsing results
parse_result = response.json()["data"]
print(f"Successfully parsed MCP service: {parse_result['url']}")
print(f"Number of tools discovered: {len(parse_result['api_info'])}")

# Display parsed tools
for i, tool in enumerate(parse_result['api_info']):
    print(f"Tool {i+1}: {tool['name']} - {tool.get('description', 'No description')}")
```

***

#### **Example: Batch Importing Tools**

After obtaining tool definitions by parsing an MCP service, you can use the following code to batch import these tools into your account:

```python
import requests

# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Assuming parse_result has been obtained (result from previous step)
# Build batch tool creation request
tools_to_create = []
for tool_info in parse_result['api_info']:
    tool_config = {
        "name": f"MCP Import: {tool_info['name']}",
        "description": tool_info.get('description', 'Tool imported from MCP service'),
        "origin": parse_result['url'],
        "path": tool_info.get('path', ''),
        "method": tool_info.get('method', 'GET'),
        "parameters": tool_info.get('parameters', []),
        "auth_config": None,
        "is_mcp_tool": True
    }
    tools_to_create.append(tool_config)

# Batch create tools
response = requests.post(
    "https://api.nuvex.ai/api/tools/create-batch",
    headers=headers,
    json={"tools": tools_to_create}
)

# Check results
result = response.json()
if result.get("code") == 0:
    created_tools = result["data"]
    print(f"Successfully imported {len(created_tools)} tools")
    for tool in created_tools:
        print(f"- Tool ID: {tool['id']}, Name: {tool['name']}")
else:
    print(f"Failed to import tools: {result.get('msg', 'Unknown error')}")
```

***

#### **Benefits of Importing MCP Tools**

* **Functionality Reuse**: No need to redevelop existing MCP tool functionality
* **Service Integration**: Combine tools from multiple MCP services into one custom MCP service
* **Feature Customization**: Selectively import needed tools, reject unwanted ones
* **Permission Control**: Apply your own access control policies to imported tools
* **Better Integration**: Seamlessly integrate third-party MCP service tools with your own developed tools

***

#### **Creating MCP Services**

**Steps to Create an MCP Service**

1. **Select tools**: Determine which tools you want to expose in the MCP service
2. **Create MCP server**: Call the `/api/mcp/create` API to register the MCP service
3. **Add prompt templates (optional)**: Use `/api/mcp/{mcp_name}/prompts`
4. **Add resources (optional)**: Use `/api/mcp/{mcp_name}/resources`

***

#### **Getting Tool IDs**

When creating an MCP service, you need to provide a list of tool IDs. These must correspond to tools already available in your Nuvex environment. Here’s how to retrieve them:

```python
import requests

# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Get list of available tools
response = requests.get(
    "https://api.nuvex.ai/api/tools/list",
    headers=headers,
    params={
        "include_public": True,    # Include public tools
        "page": 1,
        "page_size": 50
    }
)

# Parse tool list
tools_data = response.json()["data"]
available_tools = tools_data["items"]

# Display available tools and their IDs
print("Available tools list:")
for tool in available_tools:
    print(f"ID: {tool['id']} - Name: {tool['name']} - Description: {tool.get('description', 'No description')}")

# Example selected tool IDs
selected_tool_ids = [
    "00000000-0000-0000-0000-000000000001",
    "00000000-0000-0000-0000-000000000002"
]
```

***

#### **Example: Creating an MCP Service**

```python
import requests

# Use API Token
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Step 1: Get list of available tools
response = requests.get(
    "https://api.nuvex.ai/api/tools/list",
    headers=headers,
    params={"include_public": True, "page": 1, "page_size": 10}
)
tools_data = response.json()["data"]["items"]
available_tool_ids = [tool["id"] for tool in tools_data]
print(f"Available tool IDs: {available_tool_ids}")

# Step 2: Create MCP service
response = requests.post(
    "https://api.nuvex.ai/api/mcp/create",
    headers=headers,
    json={
        "mcp_name": "sample-service",
        "tool_ids": available_tool_ids[:2],  # Use the first two tools
        "description": "MCP Service Example Created with API Token"
    }
)
mcp_data = response.json()["data"]
print(f"MCP service created: {mcp_data['mcp_name']}")
```

***

#### **Step 3: Add Prompt Template**

```python
response = requests.post(
    f"https://api.nuvex.ai/api/mcp/{mcp_data['mcp_name']}/prompts",
    headers=headers,
    json={
        "prompt_name": "sample-prompt",
        "description": "Example prompt template",
        "arguments": [
            {"name": "param1", "description": "Parameter 1", "required": True}
        ],
        "template": "Use {{ param1 }} as a parameter"
    }
)
print(f"Prompt template added: {response.json()}")
```

***

#### **Step 4: Add Resource**

```python
response = requests.post(
    f"https://api.nuvex.ai/api/mcp/{mcp_data['mcp_name']}/resources",
    headers=headers,
    json={
        "resource_uri": "sample.txt",
        "content": "This is an example resource content",
        "mime_type": "text/plain"
    }
)
print(f"Resource added: {response.json()}")
```

***

#### **Example: Adding Prompt Templates**

```python
response = requests.post(
    "https://api.nuvex.ai/api/mcp/weather-service/prompts",
    headers=headers,
    json={
        "prompt_name": "check-weather",
        "description": "Query weather information for a specified city",
        "arguments": [
            {"name": "city", "description": "City name", "required": True},
            {"name": "date", "description": "Date (optional)", "required": False}
        ],
        "template": "Help me check the weather in {{ city }}{% if date %}, the date is {{ date }}{% endif %}"
    }
)

print(response.json())
```

***

#### **Example: Adding Resources**

```python
response = requests.post(
    "https://api.nuvex.ai/api/mcp/weather-service/resources",
    headers=headers,
    json={
        "resource_uri": "cities.txt",
        "content": "New York\\nLosAngeles\\nChicago\\nPhiladelphia\\n...",
        "mime_type": "text/plain"
    }
)

print(response.json())
```

***

#### **Creating MCP Services**

**Steps to Create an MCP Service**

1. **Select tools**: Determine which tools you want to expose in the MCP service
2. **Create MCP server**: Call the `/api/mcp/create` API to register the MCP service
3. **Add prompt templates (optional)**: Use `/api/mcp/{mcp_name}/prompts`
4. **Add resources (optional)**: Use `/api/mcp/{mcp_name}/resources`

***

#### **Getting Tool IDs**

When creating an MCP service, you need to provide a list of tool IDs. These must correspond to tools already available in your Nuvex environment. Here’s how to retrieve them:

```python
import requests

# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Get list of available tools
response = requests.get(
    "https://api.nuvex.ai/api/tools/list",
    headers=headers,
    params={
        "include_public": True,    # Include public tools
        "page": 1,
        "page_size": 50
    }
)

# Parse tool list
tools_data = response.json()["data"]
available_tools = tools_data["items"]

# Display available tools and their IDs
print("Available tools list:")
for tool in available_tools:
    print(f"ID: {tool['id']} - Name: {tool['name']} - Description: {tool.get('description', 'No description')}")

# Example selected tool IDs
selected_tool_ids = [
    "00000000-0000-0000-0000-000000000001",
    "00000000-0000-0000-0000-000000000002"
]
```

***

#### **Example: Creating an MCP Service**

```python
import requests

# Use API Token
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}

# Step 1: Get list of available tools
response = requests.get(
    "https://api.nuvex.ai/api/tools/list",
    headers=headers,
    params={"include_public": True, "page": 1, "page_size": 10}
)
tools_data = response.json()["data"]["items"]
available_tool_ids = [tool["id"] for tool in tools_data]
print(f"Available tool IDs: {available_tool_ids}")

# Step 2: Create MCP service
response = requests.post(
    "https://api.nuvex.ai/api/mcp/create",
    headers=headers,
    json={
        "mcp_name": "sample-service",
        "tool_ids": available_tool_ids[:2],  # Use the first two tools
        "description": "MCP Service Example Created with API Token"
    }
)
mcp_data = response.json()["data"]
print(f"MCP service created: {mcp_data['mcp_name']}")
```

***

#### **Step 3: Add Prompt Template**

```python
response = requests.post(
    f"https://api.nuvex.ai/api/mcp/{mcp_data['mcp_name']}/prompts",
    headers=headers,
    json={
        "prompt_name": "sample-prompt",
        "description": "Example prompt template",
        "arguments": [
            {"name": "param1", "description": "Parameter 1", "required": True}
        ],
        "template": "Use {{ param1 }} as a parameter"
    }
)
print(f"Prompt template added: {response.json()}")
```

***

#### **Step 4: Add Resource**

```python
response = requests.post(
    f"https://api.nuvex.ai/api/mcp/{mcp_data['mcp_name']}/resources",
    headers=headers,
    json={
        "resource_uri": "sample.txt",
        "content": "This is an example resource content",
        "mime_type": "text/plain"
    }
)
print(f"Resource added: {response.json()}")
```

***

#### **Example: Adding Prompt Templates**

```python
response = requests.post(
    "https://api.nuvex.ai/api/mcp/weather-service/prompts",
    headers=headers,
    json={
        "prompt_name": "check-weather",
        "description": "Query weather information for a specified city",
        "arguments": [
            {"name": "city", "description": "City name", "required": True},
            {"name": "date", "description": "Date (optional)", "required": False}
        ],
        "template": "Help me check the weather in {{ city }}{% if date %}, the date is {{ date }}{% endif %}"
    }
)

print(response.json())
```

***

#### **Example: Adding Resources**

```python
response = requests.post(
    "https://api.nuvex.ai/api/mcp/weather-service/resources",
    headers=headers,
    json={
        "resource_uri": "cities.txt",
        "content": "New York\\nLosAngeles\\nChicago\\nPhiladelphia\\n...",
        "mime_type": "text/plain"
    }
)

print(response.json())
```

***

#### **Using Python Client to Connect to MCP Services**

Nuvex MCP services can be accessed through various official client libraries. Below is an example using the `mcp` and `mirascope` libraries.

***

#### **Installing Dependencies**

```bash
pip install mcp mirascope
```

***

#### **Example: Using Mirascope to Connect to MCP Services**

```python
import asyncio
from mcp import ListToolsResult
from mirascope.mcp import sse_client

async def main():
    # Connect to Nuvex MCP service
    async with sse_client("https://api.nuvex.ai/mcp/mcpAggService") as client:
        # List available tools
        tools: ListToolsResult = await client._session.list_tools()
        print(tools)

if __name__ == "__main__":
    asyncio.run(main())
```

***

#### **Example: Calling MCP Tools**

```python
import asyncio
from mcp import CallToolResult
from mirascope.mcp import sse_client

async def main():
    async with sse_client("https://api.nuvex.ai/mcp/weather-service") as client:
        tools = await client._session.list_tools()
        print(f"Available tools: {[tool.name for tool in tools.tools]}")

        # Call the weather query tool
        tool_result: CallToolResult = await client._session.call_tool(
            name="query-weather",
            arguments={"city": "New York", "date": "today"}
        )

        # Print tool execution results
        for content in tool_result.contents:
            if content.type == "text":
                print(f"Result: {content.text}")
            elif content.type == "image":
                print(f"Image URL: {content.url}")

if __name__ == "__main__":
    asyncio.run(main())
```

***

#### **Example: Listing and Using Prompt Templates**

```python
import asyncio
from mirascope.mcp import sse_client

async def main():
    async with sse_client("https://api.nuvex.ai/mcp/weather-service") as client:
        prompts = await client._session.list_prompts()
        print(f"Available prompts: {[prompt.name for prompt in prompts.prompts]}")

        if prompts.prompts:
            prompt_name = prompts.prompts[0].name
            prompt = await client._session.get_prompt(
                name=prompt_name,
                arguments={"city": "Shanghai", "date": "tomorrow"}
            )
            print(f"Prompt content: {prompt.text}")

if __name__ == "__main__":
    asyncio.run(main())
```

***

#### **Example: Reading Resources**

```python
import asyncio
from mirascope.mcp import sse_client

async def main():
    async with sse_client("https://api.nuvex.ai/mcp/weather-service") as client:
        resources = await client._session.list_resources()
        print(f"Available resources: {[resource.uri for resource in resources.resources]}")

        if resources.resources:
            resource_uri = resources.resources[0].uri
            resource = await client._session.read_resource(uri=resource_uri)
            print(f"Resource content: {resource.content.text[:100]}...")  # Display first 100 characters

if __name__ == "__main__":
    asyncio.run(main())
```

***

#### **Multilingual SDK Support**

Model Context Protocol offers SDKs in multiple programming languages that can seamlessly integrate with Nuvex MCP services. Below are usage examples for TypeScript and Java.

***

#### **TypeScript / JavaScript SDK**

The TypeScript SDK is an official implementation of MCP, designed for use in Node.js and browser-based environments.

**Installation**

```bash
npm install @modelcontextprotocol/typescript-sdk
```

**Usage Example**

```typescript
import { createClient } from '@modelcontextprotocol/typescript-sdk';

async function main() {
  const client = await createClient('https://api.nuvex.ai/mcp/mcpAggService');

  try {
    const tools = await client.listTools();
    console.log('Available tools:', tools.tools.map(tool => tool.name));

    if (tools.tools.length > 0) {
      const toolName = tools.tools[0].name;
      const result = await client.callTool(toolName, {
        param1: 'value1',
        param2: 'value2'
      });

      for (const content of result.contents) {
        if (content.type === 'text') {
          console.log('Result:', content.text);
        }
      }
    }
  } finally {
    await client.close();
  }
}

main().catch(console.error);
```

For more details and advanced use cases, refer to the official TypeScript SDK repository.

***

#### **Java SDK**

The Java SDK provides full support for integrating MCP into Java applications, with first-class compatibility with frameworks like Spring AI.

**Adding Dependencies**

**Maven:**

```xml
<dependency>
  <groupId>io.modelcontextprotocol</groupId>
  <artifactId>mcp-java-sdk</artifactId>
  <version>latest-version</version>
</dependency>
```

**Gradle:**

```groovy
implementation 'io.modelcontextprotocol:mcp-java-sdk:latest-version'
```

**Usage Example**

```java
import io.modelcontextprotocol.client.MCPClient;
import io.modelcontextprotocol.client.MCPClientBuilder;
import io.modelcontextprotocol.types.CallToolResult;
import io.modelcontextprotocol.types.ListToolsResult;
import io.modelcontextprotocol.types.Tool;
import io.modelcontextprotocol.types.Content;

import java.util.HashMap;
import java.util.Map;

public class MCPExample {
    public static void main(String[] args) throws Exception {
        try (MCPClient client = MCPClientBuilder
                .create("https://api.nuvex.ai/mcp/mcpAggService")
                .build()) {

            ListToolsResult toolsResult = client.listTools();
            System.out.println("Available tools:");
            for (Tool tool : toolsResult.getTools()) {
                System.out.println("- " + tool.getName() + ": " + tool.getDescription());
            }

            if (!toolsResult.getTools().isEmpty()) {
                String toolName = toolsResult.getTools().get(0).getName();
                Map<String, Object> arguments = new HashMap<>();
                arguments.put("param1", "value1");
                arguments.put("param2", "value2");

                CallToolResult result = client.callTool(toolName, arguments);

                for (Content content : result.getContents()) {
                    if ("text".equals(content.getType())) {
                        System.out.println("Result: " + content.getText());
                    }
                }
            }
        }
    }
}
```

For more information, refer to the Java SDK official documentation.

***

#### **Advantages of MCP Services**

Using Nuvex MCP services offers the following benefits:

* **Standardized Interface**: A unified protocol for connecting to diverse data sources
* **Secure Access**: Fine-grained, token-based access control for every service call
* **Context Preservation**: Enables AI models to maintain context across tool interactions
* **Simplified Integration**: No need for custom connectors per data source
* **Scalability**: Easily add new tools and data streams as the system grows

***

#### **Practical Application Scenarios**

1. **Knowledge Base Access**\
   Connect AI agents to private or public knowledge bases, allowing them to retrieve verified answers from structured sources.
2. **Data Analysis Tools**\
   Expose analytical capabilities as MCP tools to let agents run queries and perform data transformations autonomously.
3. **Internal System Integration**\
   Bridge internal APIs (e.g., CRM, ERP) with autonomous agents via MCP wrappers, giving them real-time access and actionability.
4. **Specialized Domain Tools**\
   Offer domain-specific functions — in finance, healthcare, legal, etc. — as callable tools available to any compatible agent.

***

#### **Best Practices**

* **Tool Design**: Keep tools small and modular — one clear function per endpoint
* **Clear Descriptions**: Document tools and their parameters well for AI model understanding
* **Prompt Templates**: Include guidance templates so agents know how to invoke tools effectively
* **Resource Optimization**: Centralize common data (e.g., cities, tags, lists) as shared MCP resources
* **Permission Control**: Use token scopes or filters to limit access as needed per agent or service

***

#### **Limitations & Considerations**

* **Sync-Only Execution**: MCP tools must be fast and synchronous; long-running async jobs are not supported
* **Response Size Limits**: Avoid returning large unfiltered datasets in a single call
* **Security Hygiene**: Never return authentication keys, credentials, or internal system metadata
* **No Persistent State**: MCP server instances are created per connection and are stateless across calls

***

#### **Troubleshooting**

| Problem                   | Suggested Action                                       |
| ------------------------- | ------------------------------------------------------ |
| **Connection Fails**      | Verify MCP service name and confirm it’s been created  |
| **Auth Errors**           | Check API token validity and scope                     |
| **Tool Call Fails**       | Inspect parameter names and types — must match spec    |
| **Resource Access Fails** | Ensure the resource exists and is correctly registered |

***

#### **Summary**

Nuvex MCP services provide a standardized, secure, and developer-friendly way for AI models to access, use, and reason over live tools and data.

Through simple HTTP APIs, developers can:

* Build reusable services
* Expose internal logic to intelligent agents
* Enable composable automation across Web3 and enterprise systems
