Skip to main content

MCP Integration

A utility script to explore and interact with Model Context Protocol (MCP) tools provided by the Corvic API.

Features

  • List Tools: Dynamically fetch and display all available tools, their descriptions, and input schemas.
  • Call Tools: Invoke specific tools with custom JSON arguments via the command line.
  • Environment Support: Securely load your MCP URL and Authorization Token from a .env file.

Setup

  1. Clone or copy the files to your project directory.
  2. Create a virtual environment (recommended):
    python3 -m venv venv
    source venv/bin/activate
    
  3. Install dependencies:
    pip install mcp python-dotenv
    
  4. Configure Environment Variables: Copy the example environment file and fill in your credentials:
    cp .env.example .env
    
    Open .env and set your MCP_URL and MCP_TOKEN.

Quick Start Example

Explore MCP tools programmatically using Python:
explore_mcp_tools.py
import asyncio
import json
import argparse
import os
from typing import Optional, Dict, Any
from dotenv import load_dotenv
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

# Load environment variables from .env file
load_dotenv()

class MCPExplorer:
    def __init__(self, url: str, token: str):
        self.url = url
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "Authorization": token,
        }

    async def list_tools(self):
        """Lists all available tools and their schemas."""
        async with streamablehttp_client(self.url, headers=self.headers) as (read, write, session_id):
            async with ClientSession(read, write) as session:
                await session.initialize()
                tools_result = await session.list_tools()
                
                print("\n=== Available Tools ===")
                # list_tools returns a ListToolsResult object, which has a 'tools' attribute
                for tool in tools_result.tools:
                    print(f"\nTool: {tool.name}")
                    print(f"Description: {tool.description}")
                    print(f"Input Schema: {json.dumps(tool.inputSchema, indent=2)}")
                print("\n=======================")

    async def call_tool(self, tool_name: str, arguments: Optional[Dict[str, Any]] = None):
        """Calls a specific tool with arguments."""
        async with streamablehttp_client(self.url, headers=self.headers) as (read, write, session_id):
            async with ClientSession(read, write) as session:
                await session.initialize()
                
                print(f"\nExecuting tool: {tool_name}")
                if arguments:
                    print(f"Arguments: {json.dumps(arguments, indent=2)}")
                
                try:
                    result = await session.call_tool(tool_name, arguments=arguments or {})
                    print("\n--- Result ---")
                    print(result)
                    print("--------------")
                except Exception as e:
                    print(f"\nError calling tool '{tool_name}': {e}")

async def main():
    parser = argparse.ArgumentParser(description="MCP Tool Explorer")
    
    # Get defaults from environment variables
    env_url = os.getenv("MCP_URL")
    env_token = os.getenv("MCP_TOKEN")

    parser.add_argument("--url", default=env_url, help="MCP Server URL (can also be set via MCP_URL env var)")
    parser.add_argument("--token", default=env_token, help="Authorization Token (can also be set via MCP_TOKEN env var)")
    parser.add_argument("--list", action="store_true", help="List all available tools")
    parser.add_argument("--tool", type=str, help="Tool name to call")
    parser.add_argument("--args", type=str, help="JSON string of arguments for the tool")

    args = parser.parse_args()

    if not args.url or not args.token:
        print("Error: URL and Token are required. Provide them via CLI arguments or set MCP_URL and MCP_TOKEN in a .env file.")
        parser.print_help()
        return

    explorer = MCPExplorer(args.url, args.token)

    if args.list:
        await explorer.list_tools()
    elif args.tool:
        tool_args = {}
        if args.args:
            try:
                tool_args = json.loads(args.args)
            except json.JSONDecodeError:
                print("Error: --args must be a valid JSON string.")
                return
        await explorer.call_tool(args.tool, tool_args)
    else:
        parser.print_help()

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

Usage

List Available Tools

To see all tools supported by the agent:
python3 explore_mcp_tools.py --list

Call a Specific Tool

To execute a tool, provide its name and a JSON string for the arguments:
python3 explore_mcp_tools.py --tool query --args '{"query_content": "Who are you?"}'

Override Configuration

You can also pass the URL and Token directly via CLI arguments:
python3 explore_mcp_tools.py --url <YOUR_URL> --token <YOUR_TOKEN> --list

Detailed Tool Examples

Here are examples of how to call each available tool using the CLI:

1. Query

Ask a question to the agent:
python3 explore_mcp_tools.py --tool query --args '{"query_content": "Tell me more about the data.", "with_citation": true}'

2. Get Resource Download URL

Get URLs for specific resource IDs (usually obtained from citations in a query result):
python3 explore_mcp_tools.py --tool get_resource_download_url --args '{"resource_ids": ["res_123", "res_456"]}'

3. Get Resources

Inquire about specific file paths:
python3 explore_mcp_tools.py --tool get_resources --args '{
  "original_paths": [
    "corvic-test-container/micheldizTest/Developer_Manual.pdf",
    "corvic-test-container/micheldizTest/CorvicAPI.pdf"
  ]
}'

4. Sync Agent Data App

Trigger a synchronization of the data application:
python3 explore_mcp_tools.py --tool sync_agent_data_app

5. Deploy Agent

Deploy the agent to apply the latest changes/data:
python3 explore_mcp_tools.py --tool deploy_agent

Available MCP Tools

For detailed documentation on each MCP tool, see the MCP API Reference.