<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sofiane Ghadab on Medium]]></title>
        <description><![CDATA[Stories by Sofiane Ghadab on Medium]]></description>
        <link>https://medium.com/@thesof?source=rss-652fc735ad42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GTH2_onllVGMgS48bigZLw@2x.jpeg</url>
            <title>Stories by Sofiane Ghadab on Medium</title>
            <link>https://medium.com/@thesof?source=rss-652fc735ad42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:28:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thesof/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bridging MCP Transports: Turning an STDIO Server into SSE (and the Other Way Around)]]></title>
            <link>https://thesof.medium.com/bridging-mcp-transports-turning-an-stdio-server-into-sse-and-the-other-way-around-da23a36e074a?source=rss-652fc735ad42------2</link>
            <guid isPermaLink="false">https://medium.com/p/da23a36e074a</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[rpa-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[n8n]]></category>
            <dc:creator><![CDATA[Sofiane Ghadab]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 19:20:33 GMT</pubDate>
            <atom:updated>2025-07-15T02:37:00.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ac_20EkpUU4qRFgPQO11eQ.jpeg" /></figure><p>Model‑Context Protocol (MCP) servers come in two transport flavors:</p><ul><li><strong>STDIO</strong> — the server runs as a local process and communicates over stdin/stdout.</li><li><strong>HTTP + SSE</strong> — the server exposes an HTTP endpoint that streams replies via Server‑Sent Events.</li></ul><p>Most tools prefer one transport; some (like Cursor or VS Code) handle both. This mismatch becomes painful as your project list grows. Below you’ll learn two small utilities that let you <em>bridge</em> the gap in seconds.</p><h3>Why You Might Need a Bridge</h3><ul><li><strong>Claude Desktop</strong> (free tier) can only add <em>local STDIO</em> servers. Point it at an HTTP‑SSE server and it errors out.</li><li><strong>n8n Cloud</strong> does the opposite: it only lets you register <em>remote SSE</em> servers for security reasons.</li><li>Many open‑source MCP servers implement just one transport to stay lightweight.</li></ul><p>Instead of writing a custom wrapper, you can drop in one of the tools below.</p><h3>1 · Expose a Remote SSE Server as Local STDIO</h3><p><strong>Tool:</strong> <a href="https://www.npmjs.com/package/mcp-remote">mcp-remote</a></p><p>mcp-remote starts a small STDIO process that forwards all traffic to a remote HTTP + SSE MCP server (with optional OAuth 2.0 or Bearer‑token auth).</p><blockquote><strong><em>Security note •</em></strong><em> A critical </em><a href="https://thehackernews.com/2025/07/critical-mcp-remote-vulnerability.html"><em>RCE</em></a><em> was fixed in v0.1.16 (Jun 2025). Always pin </em><strong><em>mcp-remote@^0.1.16</em></strong><em> or later </em><strong><em>mcp-remote@latest</em></strong><em>.</em></blockquote><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;remote-example&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [<br>        &quot;mcp-remote@latest&quot;,<br>        &quot;https://remote.mcp.server/sse&quot;,<br>        &quot;--header&quot;,<br>        &quot;Authorization: Bearer ${AUTH_TOKEN}&quot;<br>      ]<br>    }<br>  },<br>  &quot;env&quot;: {<br>    &quot;AUTH_TOKEN&quot;: &quot;…&quot;<br>  }<br>}</pre><p><em>Default OAuth callback port is </em><strong><em>3333</em></strong><em>.</em><br>Need a custom one? Put it right after the URL:</p><pre>&quot;args&quot;: [<br>  &quot;mcp-remote@latest&quot;,<br>  &quot;https://remote.mcp.server/sse&quot;,<br>  &quot;3939&quot;,<br>  &quot;--header&quot;,<br>  &quot;Authorization: Bearer ${AUTH_TOKEN}&quot;<br>]</pre><p>Note: If the port is busy, mcp-remote auto‑selects a <strong>random</strong> open port.</p><h3>Quick Win: Claude Desktop ↔ n8n Cloud</h3><p>Suppose you built an n8n workflow that exposes Gmail and Google Calendar tools via an MCP <em>Server Trigger</em> secured by a Bearer token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8GbbxnC5bb7npeVnUvePg.png" /><figcaption>n8n workflow — Google Gmail and Calendar tools exposed through an MCP Server Trigger</figcaption></figure><p>Add this to claude_desktop_config.json:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;n8n (Gmail + Calendar)&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [<br>        &quot;mcp-remote@^0.1.16&quot;,<br>        &quot;https://YOUR-WORKSPACE.hooks.n8n.cloud/mcp/…/sse&quot;,<br>        &quot;--header&quot;,<br>        &quot;Authorization: Bearer ${AUTH_TOKEN}&quot;<br>      ]<br>    }<br>  },<br>  &quot;env&quot;: {<br>    &quot;AUTH_TOKEN&quot;: &quot;paste-token-from-n8n&quot;<br>  }<br>}</pre><p>Restart Claude, then ask: “Check for unread mail from Bob and put a 30‑min call on my calendar.”</p><h3>2 · Expose a Local STDIO Server as Remote SSE</h3><p><strong>Tool:</strong> <a href="https://github.com/sparfenyuk/mcp-proxy">mcp-proxy</a> by Sergey Parfenyuk (Python, bidirectional)</p><p>Install once (choose one):</p><pre># Recommended<br>uv tool install mcp-proxy<br># or<br>pipx install mcp-proxy</pre><h3>Basic Usage</h3><pre># Wrap a local Python STDIO MCP server and expose it via SSE on :8080<br>mcp-proxy --port=8080 -- uvx python-stdio-mcp-server</pre><p>Need env vars?</p><pre>mcp-proxy --env SERVICE_API_KEY=sk-… --port=8080 -- uvx python-stdio-mcp-server</pre><h3>Practical Example · Drive a Local Browser from n8n Cloud</h3><p>One long-standing gap in <strong>n8n</strong> is desktop-style automation — the keystroke-level control that classic RPA tools provide. Since v1.13, n8n can call any <strong>MCP server</strong>, so you can use something like <strong>Playwright MCP server</strong> to run browser tasks on your own machine.</p><pre>| Component                     | Transport it speaks |<br>| ----------------------------- | ------------------- |<br>| n8n **Cloud** (official SaaS) | **SSE** only        |<br>| Playwright MCP server         | **STDIO** only      |</pre><p>Because the transports don’t match, n8n Cloud can’t talk to Playwright directly.</p><h4>Work-around: mcp-proxy</h4><p>mcp-proxy starts Playwright (STDIO) and re-publishes it as an SSE endpoint that n8n Cloud <em>can</em> reach.</p><pre># 1 · Run this on the laptop that will host the browser<br>mcp-proxy --port=8080 -- npx @playwright/mcp@latest</pre><p>Your Playwright MCP server is now reachable at http://localhost:8080, but only <em>from your own machine</em>. Because <strong>n8n Cloud</strong> runs in its own VPC on the internet, it cannot open a direct connection back through your NAT/router. Use a tunnel to expose port 8080 and obtain a public HTTPS URL.</p><p>To create the tunnel, we’ll use <strong>ngrok</strong> service (see details below) because it has a generous free tier and a one‑command setup. Other tunneling service options: Cloudflare Tunnel, or Tailscale Funnel.</p><ul><li>Start the tunnel. e.g.</li></ul><pre>ngrok http 8080</pre><ul><li>Copy the generated URL into n8n as an “MCP (SSE) Server.”</li><li>Add your preferred auth (Bearer token, ngrok OAuth, IP ACL, etc.)</li></ul><p>Your cloud workflow can now click buttons and scrape pages on your local desktop — no Playwright or n8n code changes required.</p><h3>Step‑by‑Step: Set Up ngrok</h3><ul><li><strong>Create an account</strong> — go to <a href="https://dashboard.ngrok.com/">https://dashboard.ngrok.com</a>, choose the free plan, and copy your personal <em>authtoken</em>.</li><li><strong>Install the agent</strong></li></ul><p>Download &amp; install the standalone executable from the dashboard, or if you’re macOS, use Homebrew:</p><pre>brew install ngrok</pre><ul><li><strong>Save your authtoken</strong></li></ul><pre>ngrok config add-authtoken &lt;YOUR_TOKEN&gt;</pre><p>This writes ~/.config/ngrok/ngrok.yml.</p><ul><li><strong>Open the tunnel</strong></li></ul><pre>ngrok http 8080</pre><p>You’ll see something like:</p><pre>Forwarding  https://abc123.ngrok-free.app  -&gt;  http://localhost:8080</pre><ul><li><strong>Copy the HTTPS URL</strong> — that’s your new <em>remote SSE</em> endpoint.</li></ul><blockquote><strong><em>Lock it down!</em></strong><em> Before you feed real credentials or control sensitive UIs, enable at least one of:</em></blockquote><ul><li><a href="https://ngrok.com/docs/traffic-policy/actions/oauth/">ngrok OAuth</a></li><li><a href="https://ngrok.com/docs/traffic-policy/">IP allow‑list</a></li><li><a href="https://ngrok.com/docs/traffic-policy/actions/jwt/">Signed JWT</a></li></ul><h3>Final Thoughts</h3><p>With <strong>mcp‑remote</strong> and <strong>mcp‑proxy</strong> in your toolkit, you can mix‑and‑match MCP servers and clients without rewriting code. Use them to:</p><ul><li>Test a new MCP server in seconds.</li><li>Keep using familiar tools (Claude, n8n, Cursor, VS Code) despite transport quirks.</li><li>Prototype multi‑agent workflows locally, then move pieces to the cloud safely.</li></ul><p>Happy bridging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da23a36e074a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Claude: Using OpenAI and Google Gemini Models with MCP Servers]]></title>
            <link>https://thesof.medium.com/beyond-claude-using-openai-and-google-gemini-models-with-mcp-servers-eea3bc218ed0?source=rss-652fc735ad42------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea3bc218ed0</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[mcp-client]]></category>
            <dc:creator><![CDATA[Sofiane Ghadab]]></dc:creator>
            <pubDate>Sun, 11 May 2025 19:10:10 GMT</pubDate>
            <atom:updated>2025-05-11T19:10:10.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In our previous article: “<a href="https://thesof.medium.com/build-your-first-mcp-application-step-by-step-examples-for-stdio-and-sse-servers-integration-773b187aeaed">Build Your First MCP Application: Step-by-Step Examples for Stdio and SSE Servers Integration</a>”, we explored how to build an MCP client using Anthropic’s Claude. While Claude provides an excellent foundation for Model Context Protocol implementations, other leading LLMs like OpenAI’s GPT models and Google’s Gemini also offer robust function/tool calling capabilities. In this follow-up article, we’ll examine how to extend our MCP client to support these additional providers, highlighting the key differences in implementation approaches and API structures.</p><h3>Client Features</h3><p>The complete code for the updated client is provided at the bottom of this article. But here are the main features:</p><ul><li>Connect to stdio MCP servers (Python and JavaScript)</li><li>Connect to SSE MCP servers</li><li>Interactive chat interface with multiple LLM options:<br>- <strong><em>Anthropic Claude 3.5 Sonnet</em></strong> (default)<br>- <strong><em>OpenAI GPT-4o</em></strong><br>- <strong><em>Google Gemini 2.0 Flash</em></strong></li><li>Tool calling with automatic result processing</li><li>Conversation history management with refresh capability</li><li>Detailed logging for debugging and monitoring</li></ul><h3>Prerequisites</h3><ul><li>Python 3.8+</li><li>Obtain API keys for <a href="https://console.anthropic.com/settings/keys">Anthropic</a>, <a href="https://platform.openai.com/api-keys">OpenAI</a>, <a href="https://aistudio.google.com/app/apikey">Google AI</a>.</li><li>Install the required packages</li></ul><pre>pip install anthropic openai google-genai</pre><ul><li>Create a .env file with your API keys</li></ul><pre>ANTHROPIC_API_KEY=your_anthropic_api_key<br>OPENAI_API_KEY=your_openai_api_key<br>GOOGLE_API_KEY=your_google_api_key</pre><h3>The Multi-Provider MCP Client Architecture</h3><p>Our enhanced MCP client now supports three major LLM providers: Anthropic, OpenAI, and Google Gemini. This architecture allows developers to leverage different models based on their specific needs, cost considerations, or performance requirements. Let’s examine how our client initializes these providers:</p><pre>class MCPClient:<br>    def __init__(self, llm_provider: Literal[&quot;anthropic&quot;, &quot;openai&quot;, &quot;gemini&quot;] = &quot;anthropic&quot;):<br>        self.session: Optional[ClientSession] = None<br>        self.exit_stack = AsyncExitStack()<br>        self.llm_provider = llm_provider<br>        self.anthropic = None<br>        self.openai = None<br>        self.gemini = None<br>        <br>        # Initialize the selected LLM client<br>        if llm_provider == &quot;anthropic&quot;:<br>            self.anthropic = Anthropic()<br>        elif llm_provider == &quot;openai&quot;:<br>            self.openai = AsyncOpenAI()<br>        elif llm_provider == &quot;gemini&quot;:<br>            self.gemini = genai.Client()<br>        else:<br>            raise ValueError(f&quot;Unsupported LLM provider: {llm_provider}&quot;)<br>        <br>        logger.info(f&quot;Initialized MCPClient with {llm_provider} as the LLM provider&quot;)</pre><p>This design allows users to specify their preferred provider when instantiating the client:</p><pre># Using Anthropic Claude (default)<br>python client.py ./weather.py<br><br># Using OpenAI<br>python client.py ./weather.py openai<br><br># Using Google Gemini<br>python client.py ./weather.py gemini</pre><h3>Implementing OpenAI’s Tool Calling Interface</h3><p>OpenAI’s approach to function calling differs from Anthropic’s in several key aspects. Let’s examine the implementation:</p><h3>Tool Format Conversion</h3><p>First, we need to convert the MCP tool schemas into OpenAI’s expected format:</p><pre># Convert available_tools to OpenAI format<br>openai_tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: tool[&quot;name&quot;],<br>            &quot;description&quot;: tool[&quot;description&quot;],<br>            &quot;parameters&quot;: tool[&quot;input_schema&quot;]<br>        }<br>    } for tool in available_tools<br>]</pre><p>OpenAI uses a structure where each tool is wrapped in a dictionary with a “function” key, differing from Anthropic’s flatter structure.</p><h3>API Call Structure</h3><p>The OpenAI API call supports an async interface for the chat completions endpoint:</p><pre>response = await self.openai.chat.completions.create(<br>    model=model,<br>    messages=messages,<br>    tools=openai_tools,<br>    tool_choice=&quot;auto&quot;<br>)</pre><p>The tool_choice=&quot;auto&quot; parameter allows the model to decide when to call tools, similar to how Claude operates.</p><h3>Processing Tool Calls</h3><p>OpenAI’s response structure for tool calls is also different:</p><pre>response_message = response.choices[0].message<br>if response_message.tool_calls:<br>    for tool_call in response_message.tool_calls:<br>        function_name = tool_call.function.name<br>        function_args = json.loads(tool_call.function.arguments)<br>        <br>        # Execute tool call<br>        result = await self.session.call_tool(function_name, function_args)<br>        <br>        # Add tool result to messages<br>        messages.append({<br>            &quot;role&quot;: &quot;tool&quot;,<br>            &quot;tool_call_id&quot;: tool_call.id,<br>            &quot;content&quot;: result.content<br>        })</pre><p>Key differences from Anthropic’s approach:</p><ol><li>Tool calls are nested under tool_calls rather than being separate content items</li><li>Arguments are provided as a JSON string that needs parsing</li><li>Tool results are submitted with the role “tool” rather than “user” with a special structure</li></ol><h3>Follow-up Response Generation</h3><p>After tool execution, we execute another chat completion call to get the final response:</p><pre>next_response = await self.openai.chat.completions.create(<br>    model=model,<br>    messages=messages<br>)<br><br>final_text.append(next_response.choices[0].message.content)</pre><p>This pattern is similar to Claude’s, but the message structure is different.</p><h3>Implementing Google Gemini’s Tool Calling Interface</h3><p>Google’s Gemini models present the most significant implementation differences. The Gemini API uses a unique approach to tool calling with custom types and more complex interaction patterns.</p><h3>Tool Format Conversion</h3><p>Converting MCP tools to Gemini’s format requires more extensive transformation:</p><pre>def _convert_tools_to_gemini_format(self, available_tools: list) -&gt; list:<br>    &quot;&quot;&quot;Convert tools from MCP format to Gemini format.&quot;&quot;&quot;<br>    <br>    # Map JSON schema types to Gemini types<br>    type_mapping = {<br>        &quot;number&quot;: &quot;NUMBER&quot;,<br>        &quot;integer&quot;: &quot;INTEGER&quot;,<br>        &quot;boolean&quot;: &quot;BOOLEAN&quot;,<br>        &quot;array&quot;: &quot;ARRAY&quot;,<br>        &quot;object&quot;: &quot;OBJECT&quot;,<br>    }<br><br>    gemini_tools = []<br>    for tool in available_tools:<br>        # Create basic tool structure<br>        function_declaration = {<br>            &quot;name&quot;: tool[&quot;name&quot;],<br>            &quot;description&quot;: tool[&quot;description&quot;],<br>            &quot;parameters&quot;: {&quot;type&quot;: &quot;OBJECT&quot;, &quot;properties&quot;: {}, &quot;required&quot;: []}<br>        }<br>        <br>        # Convert schema if available<br>        if &quot;input_schema&quot; in tool and tool[&quot;input_schema&quot;]:<br>            schema = tool[&quot;input_schema&quot;]<br>            <br>            # Add properties from the schema<br>            if &quot;properties&quot; in schema:<br>                for prop_name, prop_details in schema[&quot;properties&quot;].items():<br>                    prop_type = prop_details.get(&quot;type&quot;, &quot;STRING&quot;).upper()<br>                    prop_type = type_mapping.get(prop_type.lower(), &quot;STRING&quot;)<br>                        <br>                    property_schema = {&quot;type&quot;: prop_type}<br>                    if &quot;description&quot; in prop_details:<br>                        property_schema[&quot;description&quot;] = prop_details[&quot;description&quot;]<br>                        <br>                    function_declaration[&quot;parameters&quot;][&quot;properties&quot;][prop_name] = property_schema<br>                    <br>            # Add required properties<br>            if &quot;required&quot; in schema:<br>                function_declaration[&quot;parameters&quot;][&quot;required&quot;] = schema[&quot;required&quot;]<br>                <br>        gemini_tools.append(function_declaration)<br>    return gemini_tools</pre><p>Gemini requires uppercase type names (like “NUMBER” instead of “number”) and has a slightly different structure for parameters.</p><h3>API Call Structure</h3><p>Gemini uses a chat-based interface with specialized types:</p><pre>gemini_tools = self._convert_tools_to_gemini_format(available_tools)<br>tools = genai_types.Tool(function_declarations=gemini_tools)<br>config = genai_types.GenerateContentConfig(tools=[tools])<br><br>chat = self.gemini.chats.create(<br>    model=model,<br>    config=config,<br>    history=chat_history<br>)<br><br>response = chat.send_message(query)</pre><p>Additionally, Gemini uses a chat object that maintains state and configuration.</p><h3>Processing Function Calls and Results</h3><p>Handling tool calls in Gemini requires careful parsing of the response structure:</p><pre>for part in candidate.content.parts:<br>    # Process text part<br>    if hasattr(part, &quot;text&quot;) and part.text:<br>        final_text.append(part.text)<br>        <br>    # Process function call part<br>    if hasattr(part, &quot;function_call&quot;) and part.function_call:<br>        function_call = part.function_call<br>        tool_name = function_call.name<br>        <br>        # Parse tool arguments<br>        tool_args = self._parse_gemini_function_args(function_call)<br>            <br>        # Execute tool call<br>        result = await self.session.call_tool(tool_name, tool_args)<br>        <br>        # Create a function response and send to Gemini for follow-up<br>        function_response_part = genai_types.Part.from_function_response(<br>            name=tool_name,<br>            response={&quot;result&quot;: result.content},<br>        )<br><br>        # Prepare contents for follow-up<br>        contents = [<br>            genai_types.Content(role=&quot;model&quot;, parts=[genai_types.Part(function_call=function_call)])<br>        ]<br>        <br>        # Add function response to contents<br>        contents.append(<br>            genai_types.Content(role=&quot;user&quot;, parts=[function_response_part])<br>        )<br>       <br>        # Send function response to get final answer<br>        follow_up_response = self.gemini.models.generate_content(<br>            model=model,<br>            config=config,<br>            contents=contents,<br>        )</pre><p>Key differences in Gemini’s approach:</p><ol><li>Function calls are contained in “parts” within the content</li><li>Arguments may require special parsing due to their object structure</li><li>Function responses must be formatted using special types</li><li>The follow-up requires constructing a new request with the original function call and its response</li></ol><h3>Performance and Reliability Observations</h3><p>During testing, we’ve observed some notable differences:</p><ol><li><strong>Anthropic Claude</strong>: Most straightforward implementation with a clean structure for tool calls and results. The API is easier to understand and debug.</li><li><strong>OpenAI GPT</strong>: Generally more reliable in tool parameter parsing, with fewer cases of malformed arguments.</li><li><strong>Google Gemini</strong>: Most complex implementation but offers fine-grained control over the conversation flow. The stateful chat object can be advantageous for maintaining context.</li></ol><h3>Code Structure for Multi-Provider Support</h3><p>To handle these different implementations, we use a strategy pattern where the main process_query method delegates to provider-specific implementations:</p><pre>async def process_query(self, query: str, previous_messages: list = None) -&gt; tuple[str, list]:<br>    &quot;&quot;&quot;Process a query using the MCP server and available tools.&quot;&quot;&quot;<br>    if not self.session:<br>        raise RuntimeError(&quot;Client session is not initialized.&quot;)<br>    <br>    # Get available tools<br>    response = await self.session.list_tools()<br>    available_tools = [{<br>        &quot;name&quot;: tool.name,<br>        &quot;description&quot;: tool.description,<br>        &quot;input_schema&quot;: dict(tool.inputSchema) if tool.inputSchema else {}<br>    } for tool in response.tools]<br>    <br>    if self.llm_provider == &quot;anthropic&quot;:<br>        return await self._process_query_anthropic(query, available_tools, previous_messages)<br>    elif self.llm_provider == &quot;openai&quot;:<br>        return await self._process_query_openai(query, available_tools, previous_messages)<br>    elif self.llm_provider == &quot;gemini&quot;:<br>        return await self._process_query_gemini(query, available_tools, previous_messages)<br>    else:<br>        raise ValueError(f&quot;Unsupported LLM provider: {self.llm_provider}&quot;)</pre><p>This design makes it easy to add support for additional providers in the future without modifying the core client functionality.</p><h3>Handling Edge Cases and Error Conditions</h3><p>Each provider has its own quirks and potential failure points:</p><h3>Anthropic Claude</h3><p>Claude occasionally provides tool arguments that don’t match the schema exactly. Adding validation or schema normalization can help:</p><pre># Example validation snippet for Claude tool args<br>def _validate_tool_args(self, tool_args, schema):<br>    # Check for required fields<br>    if &quot;required&quot; in schema:<br>        for field in schema[&quot;required&quot;]:<br>            if field not in tool_args:<br>                tool_args[field] = None  # Or provide a default value<br>    return tool_args</pre><h3>OpenAI GPT</h3><p>OpenAI may sometimes generate JSON strings with trailing commas or other minor issues:</p><pre># Example safer JSON parsing for OpenAI<br>try:<br>    function_args = json.loads(tool_call.function.arguments)<br>except json.JSONDecodeError:<br>    # Try to fix common JSON errors<br>    fixed_json = tool_call.function.arguments.replace(&#39;,}&#39;, &#39;}&#39;).replace(&#39;,]&#39;, &#39;]&#39;)<br>    function_args = json.loads(fixed_json)</pre><h3>Google Gemini</h3><p>Gemini’s complex object structure requires careful handling:</p><pre>def _parse_gemini_function_args(self, function_call):<br>    &quot;&quot;&quot;Parse function arguments from Gemini function call.&quot;&quot;&quot;<br>    tool_args = {}<br>    try:<br>        if hasattr(function_call.args, &quot;items&quot;):<br>            for k, v in function_call.args.items():<br>                tool_args[k] = v<br>        else:<br>            # Fallback if it&#39;s a string<br>            args_str = str(function_call.args)<br>            if args_str.strip():<br>                tool_args = json.loads(args_str)<br>    except Exception as e:<br>        logger.error(f&quot;Failed to parse function args: {e}&quot;, exc_info=True)<br>    return tool_args</pre><h3>Best Practices for Multi-Provider MCP Clients</h3><p>Based on our implementation experience, here are some best practices for building MCP clients that support multiple LLM providers:</p><ol><li><strong>Abstract provider-specific logic</strong>: Keep provider-specific code isolated in separate methods to maintain clean separation of concerns.</li><li><strong>Standardize return values</strong>: Ensure each provider method returns data in the same format for consistent handling by the rest of your application.</li><li><strong>Robust error handling</strong>: Add specific error handlers for each provider’s known failure modes.</li><li><strong>Consistent message history</strong>: Convert between provider-specific message formats while maintaining a consistent internal representation.</li><li><strong>Logging and monitoring</strong>: Add detailed logging specific to each provider to help debug issues:</li></ol><pre>logger.debug(f&quot;Sending query to {model} via {self.llm_provider}...&quot;)<br>logger.debug(f&quot;{self.llm_provider} response structure: {response}&quot;)</pre><h3>Conclusion</h3><p>Building an MCP client that supports multiple LLM providers requires understanding the nuances of each provider’s API. While Anthropic Claude offers the most straightforward implementation, OpenAI and Google Gemini bring their own strengths to the table.</p><p>By supporting all three providers, our enhanced MCP client gives developers the flexibility to choose the best model for their specific use case while maintaining a consistent interface for tool integration. This approach future-proofs your applications against changes in model availability, pricing, or capabilities.</p><p>As the Model Context Protocol ecosystem continues to evolve, multi-provider support will become increasingly important for building robust and flexible AI applications. By understanding the implementation differences outlined in this article, you’ll be well-equipped to navigate the complexities of integrating various LLMs with your MCP-powered tools.</p><h3>Client Full Code</h3><p>The code below is available in the Github repository <a href="https://github.com/the-sof/mcp-client/">here</a></p><pre>import asyncio<br>import sys<br>import logging<br>import json<br>import re<br><br>from typing import Optional, Literal<br>from contextlib import AsyncExitStack<br><br>from mcp import ClientSession, StdioServerParameters<br>from mcp.client.stdio import stdio_client<br>from mcp.client.sse import sse_client<br><br>from anthropic import Anthropic<br>from openai import AsyncOpenAI<br>from google import genai<br>from google.genai import types as genai_types<br><br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># Set up logger<br>logger = logging.getLogger(__name__)<br>logging.basicConfig(<br>    level=logging.INFO,<br>    format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;,<br>    handlers=[<br>        logging.FileHandler(&quot;logs/mcp_client.log&quot;),<br>        logging.StreamHandler()  # Keep console output as well<br>    ]<br>)<br><br>class MCPClient:<br>    def __init__(self, llm_provider: Literal[&quot;anthropic&quot;, &quot;openai&quot;, &quot;gemini&quot;] = &quot;anthropic&quot;):<br>        self.session: Optional[ClientSession] = None<br>        self.exit_stack = AsyncExitStack()<br>        self.llm_provider = llm_provider<br>        self.anthropic = None<br>        self.openai = None<br>        self.gemini = None<br>        <br>        # Initialize the selected LLM client<br>        if llm_provider == &quot;anthropic&quot;:<br>            self.anthropic = Anthropic()<br>        elif llm_provider == &quot;openai&quot;:<br>            self.openai = AsyncOpenAI()<br>        elif llm_provider == &quot;gemini&quot;:<br>            self.gemini = genai.Client()<br>        else:<br>            raise ValueError(f&quot;Unsupported LLM provider: {llm_provider}. Use &#39;anthropic&#39;, &#39;openai&#39;, or &#39;gemini&#39;.&quot;)<br>        <br>        logger.info(f&quot;Initialized MCPClient with {llm_provider} as the LLM provider&quot;)<br><br>    async def connect_to_sse_server(self, server_url: str):<br>        &quot;&quot;&quot;Connect to an SSE MCP server.<br>        <br>        Args:<br>            server_url (str): URL of the SSE MCP server.<br>        &quot;&quot;&quot;<br>        logger.debug(f&quot;Connecting to SSE MCP server at {server_url}&quot;)<br><br>        # Store the context managers so they stay alive<br>        self._streams_context = sse_client(url=server_url)<br>        streams = await self._streams_context.__aenter__()<br><br>        self._session_context = ClientSession(*streams)<br>        self.session: ClientSession = await self._session_context.__aenter__()<br><br>        # Initialize<br>        await self.session.initialize()<br>        <br>        # List available tools<br>        response = await self.session.list_tools()<br>        tools = response.tools<br>        logger.info(f&quot;\n\nConnected to SSE MCP Server at {server_url}. \nAvailable tools: {[tool.name for tool in tools]}&quot;)<br><br>    async def connect_to_stdio_server(self, server_script_path: str):<br>        &quot;&quot;&quot;Connect to a stdio MCP server.<br>        <br>        Args:<br>            server_script_path (str): Path to the server script (.py, .js, or npm package).<br>        &quot;&quot;&quot;<br>        is_python = False<br>        is_javascript = False<br>        command = None<br>        args = [server_script_path]<br>        <br>        # Determine if the server is a file path or npm package<br>        if server_script_path.startswith(&quot;@&quot;) or &quot;/&quot; not in server_script_path:<br>            # Assume it&#39;s an npm package<br>            is_javascript = True<br>            command = &quot;npx&quot;<br>        else:<br>            # It&#39;s a file path<br>            is_python = server_script_path.endswith(&quot;.py&quot;)<br>            is_javascript = server_script_path.endswith(&quot;.js&quot;)<br>            if not (is_python or is_javascript):<br>                raise ValueError(&quot;Server script must be a .py, .js file or npm package.&quot;)<br>        <br>            command = &quot;python&quot; if is_python else &quot;node&quot;<br>            <br>        server_params = StdioServerParameters(<br>            command=command,<br>            args=args,<br>            env=None<br>        )<br><br>        logger.debug(f&quot;\n\nConnecting to stdio MCP server with command: {command} and args: {args}&quot;)<br><br>        # Start the server<br>        stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))<br>        self.stdio, self.writer = stdio_transport<br>        self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.writer))<br><br>        await self.session.initialize()<br><br>        # List available tools<br>        response = await self.session.list_tools()<br>        tools = response.tools<br>        logger.info(f&quot;\n\nConnected to stdio MCP Server. Available tools: {[tool.name for tool in tools]}&quot;)<br><br>    async def connect_to_server(self, server_path_or_url: str):<br>        &quot;&quot;&quot;Connect to an MCP server (either stdio or SSE).<br>        <br>        Args:<br>            server_path_or_url (str): Path to the server script or URL of SSE server.<br>        &quot;&quot;&quot;<br>        # Check if the input is a URL (for SSE server)<br>        url_pattern = re.compile(r&#39;^https?://&#39;)<br>        <br>        if url_pattern.match(server_path_or_url):<br>            # It&#39;s a URL, connect to SSE server<br>            await self.connect_to_sse_server(server_path_or_url)<br>        else:<br>            # It&#39;s a script path, connect to stdio server<br>            await self.connect_to_stdio_server(server_path_or_url)<br><br>    async def process_query(self, query: str, previous_messages: list = None) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Process a query using the MCP server and available tools.<br>        <br>        Args:<br>            query (str): The query to send to the server.<br>            previous_messages (list, optional): Previous conversation history.<br><br>        Returns:<br>            tuple[str, list]: The response from the server and updated messages.<br>        &quot;&quot;&quot;<br>        if not self.session:<br>            raise RuntimeError(&quot;Client session is not initialized.&quot;)<br>        <br>        # Get available tools<br>        response = await self.session.list_tools()<br>        available_tools = [{<br>            &quot;name&quot;: tool.name,<br>            &quot;description&quot;: tool.description,<br>            &quot;input_schema&quot;: dict(tool.inputSchema) if tool.inputSchema else {}<br>        } for tool in response.tools]<br>        <br>        if self.llm_provider == &quot;anthropic&quot;:<br>            return await self._process_query_anthropic(query, available_tools, previous_messages)<br>        elif self.llm_provider == &quot;openai&quot;:<br>            return await self._process_query_openai(query, available_tools, previous_messages)<br>        elif self.llm_provider == &quot;gemini&quot;:<br>            return await self._process_query_gemini(query, available_tools, previous_messages)<br>        else:<br>            raise ValueError(f&quot;Unsupported LLM provider: {self.llm_provider}&quot;)<br>    <br>    async def _process_query_anthropic(self, query: str, available_tools: list, previous_messages: list = None) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Process a query using Anthropic&#39;s Claude.&quot;&quot;&quot;<br>        model = &quot;claude-3-5-sonnet-20241022&quot;<br>        <br>        messages = []<br>        if previous_messages:<br>            messages.extend(previous_messages)<br><br>        messages.append( <br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: query<br>            }<br>        )<br>        logger.debug(&quot;Messages sent to Claude:&quot;, messages)<br>        logger.debug(&quot;Available tools:&quot;, available_tools)<br><br>        # Initialize Claude API call<br>        logger.info(f&quot;Sending query to {model}...&quot;)<br>        response = self.anthropic.messages.create(<br>            model=model,<br>            messages=messages,<br>            tools=available_tools,<br>            max_tokens=1000<br>        )<br><br>        # Process response and handle tool calls<br>        final_text = []<br>        assistant_message_content = []<br>        logger.debug(&quot;Response from LLM:&quot;, response.content)<br><br>        for content in response.content:<br>            if content.type == &#39;text&#39;:<br>                final_text.append(content.text)<br>                assistant_message_content.append(content)<br>            elif content.type == &#39;tool_use&#39;:<br>                tool_name = content.name<br>                tool_args = content.input<br><br>                # Execute tool call<br>                logger.debug(f&quot;Calling tool {tool_name} with args {tool_args}...&quot;)<br>                final_text.append(f&quot;[Calling tool {tool_name} with args {tool_args}]&quot;)<br>                result = await self.session.call_tool(tool_name, tool_args)<br>                final_text.append(f&quot;[tool results: {result}]&quot;)<br>                <br>                assistant_message_content.append(content)<br>                messages.append({<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: assistant_message_content<br>                })<br>                messages.append({<br>                    &quot;role&quot;: &quot;user&quot;,<br>                    &quot;content&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;tool_result&quot;,<br>                            &quot;tool_use_id&quot;: content.id,<br>                            &quot;content&quot;: result.content<br>                        }<br>                    ]<br>                })<br><br>                # Get next response from Claude<br>                logger.debug(&quot;Getting next response from Claude...&quot;)<br>                logger.debug(&quot;Messages sent to Claude:&quot;, messages)<br>                next_response = self.anthropic.messages.create(<br>                    model=model,<br>                    messages=messages,<br>                    tools=available_tools,<br>                    max_tokens=1000<br>                )<br>            <br>                logger.debug(&quot;Response from Claude:&quot;, next_response.content)<br>                final_text.append(next_response.content[0].text)<br>                messages.append({<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: next_response.content[0].text<br>                })<br><br>        return &quot;\n&quot;.join(final_text), messages<br>    <br>    async def _process_query_openai(self, query: str, available_tools: list, previous_messages: list = None) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Process a query using OpenAI&#39;s GPT models.&quot;&quot;&quot;<br>        model = &quot;gpt-4o&quot;<br>        <br>        # Convert available_tools to OpenAI format<br>        openai_tools = [<br>            {<br>                &quot;type&quot;: &quot;function&quot;,<br>                &quot;function&quot;: {<br>                    &quot;name&quot;: tool[&quot;name&quot;],<br>                    &quot;description&quot;: tool[&quot;description&quot;],<br>                    &quot;parameters&quot;: tool[&quot;input_schema&quot;]<br>                }<br>            } for tool in available_tools<br>        ]<br>        <br>        messages = []<br>        if previous_messages:<br>            messages.extend(previous_messages)<br>            <br>        messages.append({<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: query<br>        })<br>        <br>        logger.debug(&quot;Messages sent to OpenAI:&quot;, messages)<br>        logger.debug(&quot;Available tools:&quot;, openai_tools)<br>        <br>        # Initialize OpenAI API call<br>        logger.info(f&quot;Sending query to {model}...&quot;)<br>        response = await self.openai.chat.completions.create(<br>            model=model,<br>            messages=messages,<br>            tools=openai_tools,<br>            tool_choice=&quot;auto&quot;<br>        )<br>        <br>        response_message = response.choices[0].message<br>        final_text = []<br>        <br>        # Process tool calls if any<br>        if response_message.tool_calls:<br>            final_text.append(response_message.content or &quot;&quot;)<br><br>            # Add the assistant&#39;s response to messages<br>            messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: response_message.content,<br>                &quot;tool_calls&quot;: response_message.tool_calls<br>            })<br>            <br>            for tool_call in response_message.tool_calls:<br>                function_name = tool_call.function.name<br>                function_args = json.loads(tool_call.function.arguments)<br>                <br>                # Execute tool call<br>                logger.debug(f&quot;Calling tool {function_name} with args {function_args}...&quot;)<br>                final_text.append(f&quot;[Calling tool {function_name} with args {function_args}]&quot;)<br>                result = await self.session.call_tool(function_name, function_args)<br>                final_text.append(f&quot;[tool results: {result}]&quot;)<br>                <br>                # Add tool result to messages<br>                messages.append({<br>                    &quot;role&quot;: &quot;tool&quot;,<br>                    &quot;tool_call_id&quot;: tool_call.id,<br>                    &quot;content&quot;: result.content<br>                })<br>            <br>            # Get the final response after tool calls<br>            logger.debug(&quot;Getting next response from OpenAI...&quot;)<br>            next_response = await self.openai.chat.completions.create(<br>                model=model,<br>                messages=messages<br>            )<br>            <br>            logger.debug(&quot;Response from OpenAI:&quot;, next_response.choices[0].message)<br>            final_text.append(next_response.choices[0].message.content)<br>            messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;, <br>                &quot;content&quot;: next_response.choices[0].message.content<br>            })<br>        else:<br>            final_text.append(response_message.content)<br>        <br>        return &quot;\n&quot;.join(final_text), messages<br>    <br>    async def _process_query_gemini(self, query: str, available_tools: list, previous_messages: list = None) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Process a query using Google&#39;s Gemini models.&quot;&quot;&quot;<br>        model = &quot;gemini-2.0-flash&quot;<br>        <br>        # Convert available_tools to a format suitable for Gemini<br>        gemini_tools = self._convert_tools_to_gemini_format(available_tools)<br>        tools = genai_types.Tool(function_declarations=gemini_tools)<br>        config = genai_types.GenerateContentConfig(tools=[tools])<br>        <br>        # Prepare chat history<br>        chat_history = self._prepare_gemini_chat_history(previous_messages)<br>        <br>        chat = self.gemini.chats.create(<br>            model=model,<br>            config=config,<br>            history=chat_history<br>        )<br>        <br>        # Initialize variables for tracking conversation<br>        final_text = []<br>        messages = previous_messages.copy() if previous_messages else []<br>        messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query})<br>        <br>        try:<br>            logger.debug(f&quot;Sending query to {model}...&quot;)<br>            response = chat.send_message(query)<br>            <br>            # Process the response<br>            final_text, messages = await self._process_gemini_response(<br>                response, <br>                final_text, <br>                messages, <br>                model, <br>                config<br>            )<br>                <br>        except Exception as e:<br>            logger.error(f&quot;Error in Gemini processing: {str(e)}&quot;, exc_info=True)<br>            final_text.append(f&quot;I encountered an error while processing your request: {str(e)}&quot;)<br>            <br>        return &quot;\n&quot;.join(final_text), messages<br>    <br>    def _convert_tools_to_gemini_format(self, available_tools: list) -&gt; list:<br>        &quot;&quot;&quot;Convert tools from MCP format to Gemini format.&quot;&quot;&quot;<br>        <br>        # Map JSON schema types to Gemini types<br>        type_mapping = {<br>            &quot;number&quot;: &quot;NUMBER&quot;,<br>            &quot;integer&quot;: &quot;INTEGER&quot;,<br>            &quot;boolean&quot;: &quot;BOOLEAN&quot;,<br>            &quot;array&quot;: &quot;ARRAY&quot;,<br>            &quot;object&quot;: &quot;OBJECT&quot;,<br>        }<br><br>        gemini_tools = []<br>        for tool in available_tools:<br>            # Create basic tool structure<br>            function_declaration = {<br>                &quot;name&quot;: tool[&quot;name&quot;],<br>                &quot;description&quot;: tool[&quot;description&quot;],<br>                &quot;parameters&quot;: {&quot;type&quot;: &quot;OBJECT&quot;, &quot;properties&quot;: {}, &quot;required&quot;: []}<br>            }<br>            <br>            # Convert schema if available<br>            if &quot;input_schema&quot; in tool and tool[&quot;input_schema&quot;]:<br>                schema = tool[&quot;input_schema&quot;]<br>                <br>                # Add properties from the schema<br>                if &quot;properties&quot; in schema:<br>                    for prop_name, prop_details in schema[&quot;properties&quot;].items():<br>                        prop_type = prop_details.get(&quot;type&quot;, &quot;STRING&quot;).upper()<br>                        prop_type = type_mapping.get(prop_type.lower(), &quot;STRING&quot;)<br>                            <br>                        property_schema = {&quot;type&quot;: prop_type}<br>                        if &quot;description&quot; in prop_details:<br>                            property_schema[&quot;description&quot;] = prop_details[&quot;description&quot;]<br>                            <br>                        function_declaration[&quot;parameters&quot;][&quot;properties&quot;][prop_name] = property_schema<br>                        <br>                # Add required properties<br>                if &quot;required&quot; in schema:<br>                    function_declaration[&quot;parameters&quot;][&quot;required&quot;] = schema[&quot;required&quot;]<br>                    <br>            gemini_tools.append(function_declaration)<br>        return gemini_tools<br>    <br>    def _prepare_gemini_chat_history(self, previous_messages: list) -&gt; list:<br>        &quot;&quot;&quot;Prepare chat history in Gemini&#39;s format.&quot;&quot;&quot;<br>        chat_history = []<br>        if not previous_messages:<br>            return chat_history<br>            <br>        for message in previous_messages:<br>            if message[&quot;role&quot;] == &quot;user&quot; and isinstance(message[&quot;content&quot;], str):<br>                chat_history.append({<br>                    &quot;role&quot;: &quot;user&quot;,<br>                    &quot;parts&quot;: [{&quot;text&quot;: message[&quot;content&quot;]}]<br>                })<br>            elif message[&quot;role&quot;] == &quot;assistant&quot; and isinstance(message[&quot;content&quot;], str):<br>                chat_history.append({<br>                    &quot;role&quot;: &quot;model&quot;,<br>                    &quot;parts&quot;: [{&quot;text&quot;: message[&quot;content&quot;]}]<br>                })<br>        return chat_history<br>    <br>    async def _process_gemini_response(self, response, final_text, messages, model, config):<br>        &quot;&quot;&quot;Process the response from Gemini, including any function calls.&quot;&quot;&quot;<br>        if not hasattr(response, &quot;candidates&quot;) or not response.candidates:<br>            logger.warning(&quot;No candidates in Gemini response&quot;)<br>            final_text.append(&quot;I couldn&#39;t generate a proper response.&quot;)<br>            return final_text, messages<br>            <br>        candidate = response.candidates[0]<br>        if not hasattr(candidate, &quot;content&quot;) or not hasattr(candidate.content, &quot;parts&quot;):<br>            logger.warning(&quot;No content or parts in Gemini response&quot;)<br>            final_text.append(&quot;I received an incomplete response.&quot;)<br>            return final_text, messages<br>            <br>        # Process text and function calls<br>        for part in candidate.content.parts:<br>            # Process text part<br>            if hasattr(part, &quot;text&quot;) and part.text:<br>                final_text.append(part.text)<br>                <br>            # Process function call part<br>            if hasattr(part, &quot;function_call&quot;) and part.function_call:<br>                function_call = part.function_call<br>                tool_name = function_call.name<br>                <br>                # Parse tool arguments<br>                tool_args = self._parse_gemini_function_args(function_call)<br>                    <br>                # Add function call info to response<br>                function_call_text = f&quot;I need to call the {tool_name} function to help with your request.&quot;<br>                final_text.append(function_call_text)<br>                <br>                # Execute tool call<br>                try:<br>                    logger.debug(f&quot;Calling tool {tool_name} with args {tool_args}...&quot;)<br>                    final_text.append(f&quot;[Calling tool {tool_name} with args {tool_args}]&quot;)<br>                    result = await self.session.call_tool(tool_name, tool_args)<br>                    final_text.append(f&quot;[tool results: {result}]&quot;)<br>                    <br>                    # Create a function response and send to Gemini for follow-up<br>                    final_text, messages = await self._handle_tool_result(<br>                        tool_name, <br>                        function_call, <br>                        result, <br>                        final_text, <br>                        messages,<br>                        model,<br>                        config<br>                    )<br>                except Exception as e:<br>                    error_msg = f&quot;Error executing tool {tool_name}: {str(e)}&quot;<br>                    logger.error(error_msg, exc_info=True)<br>                    final_text.append(error_msg)<br>                <br>        return final_text, messages<br>    <br>    def _parse_gemini_function_args(self, function_call):<br>        &quot;&quot;&quot;Parse function arguments from Gemini function call.&quot;&quot;&quot;<br>        tool_args = {}<br>        try:<br>            if hasattr(function_call.args, &quot;items&quot;):<br>                for k, v in function_call.args.items():<br>                    tool_args[k] = v<br>            else:<br>                # Fallback if it&#39;s a string<br>                args_str = str(function_call.args)<br>                if args_str.strip():<br>                    tool_args = json.loads(args_str)<br>                    <br>            logger.debug(f&quot;Parsed tool args: {tool_args}&quot;)<br>        except Exception as e:<br>            logger.error(f&quot;Failed to parse function args: {e} - {type(function_call.args)}&quot;, exc_info=True)<br>            <br>        return tool_args<br>    <br>    async def _handle_tool_result(self, tool_name, function_call, result, final_text, messages, model, config):<br>        &quot;&quot;&quot;Handle the result of a tool call and get follow-up response.&quot;&quot;&quot;<br>        try:<br>            # Prepare function response<br>            function_response_part = genai_types.Part.from_function_response(<br>                name=tool_name,<br>                response={&quot;result&quot;: result.content if hasattr(result, &quot;content&quot;) else str(result)},<br>            )<br><br>            # Prepare contents for follow-up<br>            contents = [<br>                genai_types.Content(<br>                    role=&quot;model&quot;, <br>                    parts=[genai_types.Part(function_call=function_call)]<br>                )<br>            ]<br>            <br>            # Add to messages history                               <br>            messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;, <br>                &quot;content&quot;: function_call.model_dump_json()<br>            })<br><br>            # Add function response to contents<br>            contents.append(<br>                genai_types.Content(<br>                    role=&quot;user&quot;, <br>                    parts=[function_response_part]<br>                )<br>            )<br>            <br>            # Add to messages history<br>            result_content = result.content if hasattr(result, &quot;content&quot;) else str(result)                           <br>            messages.append({<br>                &quot;role&quot;: &quot;user&quot;, <br>                &quot;content&quot;: {&quot;result&quot;: result_content}<br>            })<br>           <br>            # Send function response to get final answer<br>            follow_up_response = self.gemini.models.generate_content(<br>                model=model,<br>                config=config,<br>                contents=contents,<br>            )<br>            <br>            # Extract text from follow-up response<br>            if hasattr(follow_up_response, &quot;candidates&quot;) and follow_up_response.candidates:<br>                follow_up_candidate = follow_up_response.candidates[0]<br>                if (hasattr(follow_up_candidate, &quot;content&quot;) and <br>                    hasattr(follow_up_candidate.content, &quot;parts&quot;)):<br>                    <br>                    follow_up_text = &quot;&quot;<br>                    for follow_up_part in follow_up_candidate.content.parts:<br>                        if hasattr(follow_up_part, &quot;text&quot;):<br>                            follow_up_text += follow_up_part.text<br>                            <br>                    if follow_up_text:<br>                        final_text.append(follow_up_text)<br>                        messages.append({<br>                            &quot;role&quot;: &quot;assistant&quot;, <br>                            &quot;content&quot;: follow_up_text<br>                        })<br>                    else:<br>                        final_text.append(&quot;I received the tool results but couldn&#39;t generate a follow-up response.&quot;)<br>                        <br>            else:<br>                final_text.append(&quot;I processed your request but couldn&#39;t generate a follow-up response.&quot;)<br>                <br>        except Exception as e:<br>            logger.error(f&quot;Error in follow-up response: {str(e)}&quot;, exc_info=True)<br>            final_text.append(f&quot;I received the tool results but encountered an error: {str(e)}&quot;)<br>            <br>        return final_text, messages<br><br>    async def chat_loop(self):<br>        &quot;&quot;&quot;Run an interactive chat loop with the server.&quot;&quot;&quot;<br>        previous_messages = []<br>        print(&quot;Type your queries or &#39;quit&#39; to exit.&quot;)<br>        print(&quot;Type &#39;refresh&#39; to clear conversation history.&quot;)<br>        print(f&quot;Using {self.llm_provider.upper()} as the LLM provider.&quot;)<br>        <br>        while True:<br>            try:<br>                query = input(&quot;\nQuery: &quot;).strip()<br>                if query.lower() == &quot;quit&quot;:<br>                    break<br>                <br>                #  Check if the user wants to refresh conversation (history)<br>                if query.lower() == &quot;refresh&quot;:<br>                    previous_messages = []<br>                    print(&quot;Conversation history cleared.&quot;)<br>                    continue<br>            <br>                response, previous_messages = await self.process_query(query, previous_messages=previous_messages)<br>                print(&quot;\nResponse:&quot;, response)<br>            except Exception as e:<br>                logger.exception(&quot;Error in chat loop&quot;)<br>                print(&quot;Error:&quot;, str(e))<br><br>    async def clenup(self):<br>        &quot;&quot;&quot;Clean up resources.&quot;&quot;&quot;<br>        await self.exit_stack.aclose()<br>        if hasattr(self, &#39;_session_context&#39;) and self._session_context:<br>            await self._session_context.__aexit__(None, None, None)<br>        if hasattr(self, &#39;_streams_context&#39;) and self._streams_context:<br>            await self._streams_context.__aexit__(None, None, None)<br><br><br>async def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python client.py &lt;server_script_path_or_url&gt; [llm_provider]&quot;)<br>        print(&quot;Examples:&quot;)<br>        print(&quot;  - stdio server (npm): python client.py @playwright/mcp@latest&quot;)<br>        print(&quot;  - stdio server (python): python client.py ./weather.py&quot;)<br>        print(&quot;  - SSE server: python client.py http://localhost:3000/mcp&quot;)<br>        print(&quot;  - Specify LLM provider: python client.py ./weather.py openai&quot;)<br>        print(&quot;  - Use Gemini: python client.py ./weather.py gemini&quot;)<br>        sys.exit(1)<br><br>    # Default to anthropic if provider isn&#39;t specified<br>    llm_provider = &quot;anthropic&quot;<br>    if len(sys.argv) &gt; 2 and sys.argv[2].lower() in [&quot;anthropic&quot;, &quot;openai&quot;, &quot;gemini&quot;]:<br>        llm_provider = sys.argv[2].lower()<br><br>    client = MCPClient(llm_provider=llm_provider)<br>    try:<br>        await client.connect_to_server(sys.argv[1])<br>        await client.chat_loop()<br>    finally:<br>        await client.clenup()<br>        print(&quot;\nMCP Client Closed!&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea3bc218ed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First MCP Application: Step-by-Step Examples for Stdio and SSE Servers Integration]]></title>
            <link>https://thesof.medium.com/build-your-first-mcp-application-step-by-step-examples-for-stdio-and-sse-servers-integration-773b187aeaed?source=rss-652fc735ad42------2</link>
            <guid isPermaLink="false">https://medium.com/p/773b187aeaed</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[automation-software]]></category>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Sofiane Ghadab]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 15:26:10 GMT</pubDate>
            <atom:updated>2025-05-11T19:15:38.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Building AI applications with tool-based interactions has traditionally been challenging. In a previous <a href="https://medium.com/@thesof/using-langchain-agents-to-invoke-a-robotics-process-automation-rpa-a-quick-intro-716a5bb711ae">article</a>, we provided a quick intro on function calling using <strong><em>Langchain</em></strong>. The Model Context Protocol (MCP) offers a more standardized approach to enable AI models to interact with external tools seamlessly. In this article, we’ll explore how to create MCP clients that can communicate with both <strong><em>stdio</em></strong> and<strong><em> SSE</em></strong> MCP servers.</p><h3>What is the Model Context Protocol?</h3><p>The Model Context Protocol (MCP) is an open standard that defines how AI systems interact with external tools, capabilities, and information sources. MCP creates a standardized communication protocol between AI models and the tools they need to access, making it easier to build AI applications with consistent tool interactions.</p><p>According to the <a href="https://modelcontextprotocol.io/introduction">official documentation</a>, MCP aims to provide:</p><ol><li>A standard interface for AI models to discover and use tools</li><li>A consistent way to execute tools and return results</li><li>A model-agnostic approach applicable across different AI providers</li></ol><p>MCP enables AI systems to:</p><ul><li>Discover available tools</li><li>Learn how to use them through schema definitions</li><li>Execute tools and receive results</li><li>Handle errors gracefully</li></ul><h3>Understanding stdio vs SSE MCP Servers</h3><p>MCP supports two primary transport mechanisms for communication between clients and servers:</p><h4>stdio MCP Servers</h4><p>Standard Input/Output (stdio) servers operate through command-line interfaces using stdin and stdout streams. They are:</p><ul><li><strong>Process-based</strong>: Started as child processes by the client</li><li><strong>Simple to implement</strong>: Just read from stdin and write to stdout</li><li><strong>Suitable for local tools</strong>: Ideal for tools that run on the same machine</li><li><strong>Examples</strong>: CLI-based local services, file operations, or local database queries</li></ul><h4>Server-Sent Events (SSE) MCP Servers</h4><p>SSE servers use HTTP-based communication with the Server-Sent Events protocol. They are:</p><ul><li><strong>Network-based</strong>: Communicate over HTTP, accessible via URLs</li><li><strong>Scalable</strong>: Can be hosted remotely and accessed by multiple clients</li><li><strong>Stateful</strong>: Maintain persistent connections</li><li><strong>Examples</strong>: Web-based services, cloud APIs, or distributed systems</li></ul><h3>Building an MCP Client in Python</h3><p>Now, let’s build a versatile Python MCP client that can interact with both stdio and SSE MCP servers. We’ll use the mcp Python package along with Claude from Anthropic to process our queries.</p><h4>Setting Up Your Environment</h4><p>First, let’s set up a Python virtual environment:</p><pre># Create a virtual environment<br>python -m venv .venv<br><br># Activate the environment<br># On macOS/Linux<br>source .venv/bin/activate<br># On Windows<br>.venv\Scripts\activate<br><br># Install required packages<br>pip install mcp-python anthropic aiohttp python-dotenv</pre><h4>LLM Compatibility</h4><p>While our example uses Claude 3.5 Sonnet, most modern LLMs that support function calling should work. This includes:</p><ul><li>OpenAI’s GPT models (via the <a href="https://pypi.org/project/openai/">openai</a> Python package)</li><li>Google’s Gemini models (via the <a href="https://pypi.org/project/google-genai/">google-genai</a> package)</li><li>Anthropic’s Claude models (as shown in our example)</li></ul><p>The key requirement is that the LLM must support tool/function calling with a JSON schema interface. You would simply need to modify the process_query method to use your preferred LLM’s API structure.</p><p>In part II of this article, “<a href="https://medium.com/@thesof/beyond-claude-using-openai-and-google-gemini-models-with-mcp-servers-eea3bc218ed0?source=your_stories_page--------------------------------------------">Beyond Claude: Using OpenAI and Google Gemini Models with MCP Servers</a>”, we show how this is implemented.</p><p>Create a <em>.env</em> file with your Anthropic API key:</p><pre>ANTHROPIC_API_KEY=your_api_key_here</pre><h4>Building the MCP Client</h4><p>Our client is based on the example provided in the <a href="https://modelcontextprotocol.io/quickstart/client">official user guide</a>, however, in our case, it handles <strong><em>both</em></strong> stdio and SSE servers. Here’s our implementation:</p><pre>import asyncio<br>import sys<br>import logging<br>import json<br>import os<br>import re<br><br>from typing import Optional<br>from contextlib import AsyncExitStack<br><br>from mcp import ClientSession, StdioServerParameters<br>from mcp.client.stdio import stdio_client<br>from mcp.client.sse import sse_client<br><br>from anthropic import Anthropic<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># Set up logger<br>logger = logging.getLogger(__name__)<br>logging.basicConfig(<br>    level=logging.INFO,<br>    format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;,<br>    handlers=[<br>        logging.FileHandler(&quot;logs/mcp_client.log&quot;),<br>        logging.StreamHandler()<br>    ]<br>)<br><br>class MCPClient:<br>    def __init__(self):<br>        self.session = None<br>        self.exit_stack = AsyncExitStack()<br>        self.anthropic = Anthropic()<br><br>    async def connect_to_sse_server(self, server_url: str):<br>        &quot;&quot;&quot;Connect to an SSE MCP server.&quot;&quot;&quot;<br>        logger.debug(f&quot;Connecting to SSE MCP server at {server_url}&quot;)<br><br>        self._streams_context = sse_client(url=server_url)<br>        streams = await self._streams_context.__aenter__()<br><br>        self._session_context = ClientSession(*streams)<br>        self.session = await self._session_context.__aenter__()<br><br>        # Initialize<br>        await self.session.initialize()<br>        <br>        # List available tools<br>        response = await self.session.list_tools()<br>        tools = response.tools<br>        logger.info(f&quot;Connected to SSE MCP Server at {server_url}. Available tools: {[tool.name for tool in tools]}&quot;)<br><br>    async def connect_to_stdio_server(self, server_script_path: str):<br>        &quot;&quot;&quot;Connect to a stdio MCP server.&quot;&quot;&quot;<br>        is_python = False<br>        is_javascript = False<br>        command = None<br>        args = [server_script_path]<br>        <br>        # Determine if the server is a file path or npm package<br>        if server_script_path.startswith(&quot;@&quot;) or &quot;/&quot; not in server_script_path:<br>            # Assume it&#39;s an npm package<br>            is_javascript = True<br>            command = &quot;npx&quot;<br>        else:<br>            # It&#39;s a file path<br>            is_python = server_script_path.endswith(&quot;.py&quot;)<br>            is_javascript = server_script_path.endswith(&quot;.js&quot;)<br>            if not (is_python or is_javascript):<br>                raise ValueError(&quot;Server script must be a .py, .js file or npm package.&quot;)<br>        <br>            command = &quot;python&quot; if is_python else &quot;node&quot;<br>            <br>        server_params = StdioServerParameters(<br>            command=command,<br>            args=args,<br>            env=None<br>        )<br><br>        logger.debug(f&quot;Connecting to stdio MCP server with command: {command} and args: {args}&quot;)<br><br>        # Start the server<br>        stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))<br>        self.stdio, self.writer = stdio_transport<br>        self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.writer))<br><br>        await self.session.initialize()<br><br>        # List available tools<br>        response = await self.session.list_tools()<br>        tools = response.tools<br>        logger.info(f&quot;Connected to stdio MCP Server. Available tools: {[tool.name for tool in tools]}&quot;)<br><br>    async def connect_to_server(self, server_path_or_url: str):<br>        &quot;&quot;&quot;Connect to an MCP server (either stdio or SSE).&quot;&quot;&quot;<br>        # Check if the input is a URL (for SSE server)<br>        url_pattern = re.compile(r&#39;^https?://&#39;)<br>        <br>        if url_pattern.match(server_path_or_url):<br>            # It&#39;s a URL, connect to SSE server<br>            await self.connect_to_sse_server(server_path_or_url)<br>        else:<br>            # It&#39;s a script path, connect to stdio server<br>            await self.connect_to_stdio_server(server_path_or_url)<br><br>    async def process_query(self, query: str, previous_messages: list = None) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Process a query using the MCP server and available tools.&quot;&quot;&quot;<br>        model = &quot;claude-3-5-sonnet-20241022&quot;<br><br>        if not self.session:<br>            raise RuntimeError(&quot;Client session is not initialized.&quot;)<br>        <br>        messages = []<br>        if previous_messages:<br>            messages.extend(previous_messages)<br><br>        messages.append( <br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: query<br>            }<br>        )<br>        <br>        response = await self.session.list_tools()<br>        available_tools = [{<br>            &quot;name&quot;: tool.name,<br>            &quot;description&quot;: tool.description,<br>            &quot;input_schema&quot;: dict(tool.inputSchema) if tool.inputSchema else {}<br>             } for tool in response.tools]<br><br>        # Initialize Claude API call<br>        logger.info(f&quot;Sending query to {model}...&quot;)<br>        response = self.anthropic.messages.create(<br>            model=model,<br>            messages=messages,<br>            tools=available_tools,<br>            max_tokens=1000<br>        )<br><br>        # Process response and handle tool calls<br>        final_text = []<br>        assistant_message_content = []<br><br>        for content in response.content:<br>            if content.type == &#39;text&#39;:<br>                final_text.append(content.text)<br>                assistant_message_content.append(content)<br>            elif content.type == &#39;tool_use&#39;:<br>                tool_name = content.name<br>                tool_args = content.input<br><br>                # Execute tool call<br>                logger.debug(f&quot;Calling tool {tool_name} with args {tool_args}...&quot;)<br>                result = await self.session.call_tool(tool_name, tool_args)<br>                final_text.append(f&quot;[Calling tool {tool_name} with args {tool_args}]&quot;)<br>                <br>                assistant_message_content.append(content)<br>                messages.append({<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: assistant_message_content<br>                })<br>                messages.append({<br>                    &quot;role&quot;: &quot;user&quot;,<br>                    &quot;content&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;tool_result&quot;,<br>                            &quot;tool_use_id&quot;: content.id,<br>                            &quot;content&quot;: result.content<br>                        }<br>                    ]<br>                })<br><br>                # Get next response from Claude<br>                next_response = self.anthropic.messages.create(<br>                    model=model,<br>                    messages=messages,<br>                    tools=available_tools,<br>                    max_tokens=1000<br>                )<br>            <br>                final_text.append(next_response.content[0].text)<br>                messages.append({<br>                    &quot;role&quot;: &quot;assistant&quot;,<br>                    &quot;content&quot;: next_response.content[0].text<br>                })<br><br>        return &quot;\n&quot;.join(final_text), messages<br>    <br>    async def chat_loop(self):<br>        &quot;&quot;&quot;Run an interactive chat loop with the server.&quot;&quot;&quot;<br>        previous_messages = []<br>        print(&quot;Type your queries or &#39;quit&#39; to exit.&quot;)<br>        <br>        while True:<br>            try:<br>                query = input(&quot;\nQuery: &quot;).strip()<br>                if query.lower() == &quot;quit&quot;:<br>                    break<br>                <br>                #  Check if the user wants to refresh conversation (history)<br>                if query.lower() == &quot;refresh&quot;:<br>                    previous_messages = []<br>            <br>                response, previous_messages = await self.process_query(query, previous_messages=previous_messages)<br>                print(&quot;\nResponse:&quot;, response)<br>            except Exception as e:<br>                print(&quot;Error:&quot;, str(e))<br><br>    async def clenup(self):<br>        &quot;&quot;&quot;Clean up resources.&quot;&quot;&quot;<br>        await self.exit_stack.aclose()<br>        if hasattr(self, &#39;_session_context&#39;) and self._session_context:<br>            await self._session_context.__aexit__(None, None, None)<br>        if hasattr(self, &#39;_streams_context&#39;) and self._streams_context:<br>            await self._streams_context.__aexit__(None, None, None)<br><br><br>async def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python client.py &lt;server_script_path_or_url&gt;&quot;)<br>        print(&quot;Examples:&quot;)<br>        print(&quot;  - stdio MCP server (npm): python client.py @playwright/mcp@latest&quot;)<br>        print(&quot;  - stdio MCP server (python): python client.py ./weather.py&quot;)<br>        print(&quot;  - SSE MCP server: python client.py http://localhost:3000/mcp&quot;)<br>        sys.exit(1)<br><br>    client = MCPClient()<br>    try:<br>        await client.connect_to_server(sys.argv[1])<br>        await client.chat_loop()<br>    finally:<br>        await client.clenup()<br>        print(&quot;\nMCP Client Closed!&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><h4>Understanding the MCP Client Connection Logic</h4><p>Let’s break down the two key connection methods in our MCP client implementation: connect_to_stdio_server() and connect_to_server(). These methods are crucial for establishing connections to different types of MCP servers.</p><h4>The connect_to_stdio_server() Method</h4><p>This method handles connecting to a stdio-based MCP server, which operates over standard input/output streams. Here’s how it works:</p><p><strong>Server Type Detection</strong>:</p><ul><li>First, it analyzes the server_script_path parameter to determine what type of server we’re dealing with</li><li>If the path starts with @ or doesn&#39;t contain a / character, it&#39;s treated as an npm package (like @playwright/mcp@latest)</li><li>Otherwise, it looks at file extensions to determine if it’s a Python (.py) or JavaScript (.js) file</li></ul><p><strong>Command Selection</strong>:</p><ul><li>For npm packages, it uses the npx command to execute the package</li><li>For Python scripts, it uses the python command</li><li>For JavaScript files, it uses the node command</li></ul><p><strong>Server Parameters Configuration</strong>:</p><ul><li>Creates a StdioServerParameters object with the appropriate command, arguments, and environment variables</li></ul><p><strong>Server Startup</strong>:</p><ul><li>Uses the MCP library’s stdio_client function to <strong><em>start the server process locally</em></strong></li><li>Manages the process lifecycle with AsyncExitStack to ensure proper cleanup when done</li></ul><p><strong>Session Establishment</strong>:</p><ul><li>Creates a ClientSession with the stdio streams returned by the server startup</li><li>Calls initialize() to establish the MCP connection</li></ul><p><strong>Tool Discovery</strong>:</p><ul><li>Calls list_tools() to query what capabilities the server provides</li><li>Logs the available tools to help users understand what the server can do</li></ul><h4>The connect_to_sse_server() Method</h4><p>This method establishes a connection to an HTTP-based SSE (Server-Sent Events) MCP server. It assumes the service is already up and listening on the dedicated port:</p><p><strong>Context Creation</strong>:</p><ul><li>Creates an SSE client context using sse_client(url=server_url)</li><li>Stores it in self._streams_context to ensure it remains alive throughout the session</li><li>The __aenter__ method establishes the HTTP connection and returns the stream objects</li></ul><p><strong>Stream Handling</strong>:</p><ul><li>Unlike stdio which uses a subprocess, SSE uses HTTP streaming connections</li><li>The streams variable contains reader/writer objects for the SSE connection</li></ul><p><strong>Session Establishment</strong>:</p><ul><li>Creates a ClientSession using the SSE streams</li><li>The session provides the same high-level API as with stdio servers, abstracting the transport details</li><li>Stores the session context in self._session_context for proper cleanup later</li></ul><p><strong>Protocol Initialization</strong>:</p><ul><li>Just like with stdio, calls session.initialize() to perform the MCP protocol handshake</li></ul><p><strong>Tool Discovery</strong>:</p><ul><li>Calls session.list_tools() to query the server for available tools</li><li>Logs information about the successful connection and available tools</li></ul><h4>Key Differences Between the Connection Methods</h4><p><strong>Transport Mechanism</strong>:</p><ul><li>connect_to_stdio_server(): Uses standard input/output of a subprocess</li><li>connect_to_sse_server(): Uses HTTP with Server-Sent Events over the network</li></ul><p><strong>Server Launch</strong>:</p><ul><li>connect_to_stdio_server(): Launches the server as a local process</li><li>connect_to_sse_server(): Connects to an already-running server via HTTP</li></ul><p><strong>Server Identification</strong>:</p><ul><li>connect_to_stdio_server(): Identifies server type by file extension or package format</li><li>connect_to_sse_server(): Simply uses the provided URL</li></ul><p><strong>Context Management</strong>:</p><ul><li>Both methods use async context managers but for different types of resources</li><li>stdio manages subprocess lifecycle</li><li>SSE manages HTTP connection lifecycle</li></ul><h3>Examples of Using MCP Servers</h3><p>Let’s explore examples with both stdio and SSE MCP servers. This <a href="https://github.com/modelcontextprotocol/servers">repository</a> has an extensive collection of reference MCP servers implementations, as well as references to community built servers.</p><h4>MCP Inspector</h4><p>One handy tool for testing and debugging MCP server is the <a href="https://modelcontextprotocol.io/docs/tools/inspector"><strong><em>MCP Inspector</em></strong>.</a></p><p>The Inspector runs directly through <strong>npx</strong> without requiring installation:</p><pre>npx @modelcontextprotocol/inspector &lt;command&gt;</pre><p>To test our client, we’ll use three MCP servers:</p><ul><li>The Python weather service MCP server built <a href="https://modelcontextprotocol.io/quickstart/server">here</a> that retrieves current forecast conditions for a specified location.</li><li>The npm package <a href="https://github.com/microsoft/playwright-mcp"><strong>microsoft/playwright-mcp</strong></a><strong> </strong>which is a wrapper to the Microsoft open source testing <a href="https://playwright.dev/">framework</a> for web applications (it allows developers/testers to automate browser actions).</li><li>The SSE MCP server <a href="https://github.com/co-browser/browser-use-mcp-server/">wrapper </a>of the amazing browser automation tool, <a href="https://browser-use.com/"><strong><em>Browser Use</em></strong></a>. The tool allows the AI to interact with web pages.</li></ul><p>To view the above servers in in MCP inspector:</p><p><strong>weather.py</strong>:</p><p>In a terminal window/command line, use the command below to launch the MCP Inspector with the weather service MCP server</p><pre>% npx @modelcontextprotocol/inspector \                              <br>  uv \<br>  --directory &lt;path&gt;/ \<br>  run \<br>  weather.py</pre><p>(replace &lt;path&gt; with the full path to your weather.py file)<br>Once you hit enter you will be asked to install the MCP Inspector npm package</p><pre>Need to install the following packages:<br>@modelcontextprotocol/inspector@0.9.0<br>Ok to proceed? (y) y<br><br>Starting MCP inspector...<br>⚙️ Proxy server listening on port 6277<br>🔍 MCP Inspector is up and running at http://127.0.0.1:6274</pre><p>Once you navigate to <a href="http://127.0.0.1:6274/">http://127.0.0.1:6274</a> and hit connect, you can explore your MCP Server tools, prompts and resources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7IusQN8auTokDYcuB3VhQ.png" /><figcaption>MCP Inspector — weather.py</figcaption></figure><p><strong>@playwright/mcp</strong>:</p><p>Use the command below to launch the MCP Inspector with playwright-mcp</p><pre>npx @modelcontextprotocol/inspector npx @playwright/mcp@latest </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlfmrp7jq4nQMYpG9Ts-bQ.png" /><figcaption>MCP Inspector — <a href="http://twitter.com/playwright/mcp">@playwright/mcp</a>@latest</figcaption></figure><p><strong>browser-use-mcp-server</strong>:</p><p>Follow the instructions in the <a href="https://github.com/co-browser/browser-use-mcp-server/tree/main">README</a> to run the server in SSE Mode, either locally, or in a Docker container.</p><p>Assuming you have a browser use SSE MCP server running on <em>localhost:8000/sse</em>, use the command below to launch the MCP Inspector with browser-use-mcp-server</p><pre>npx @modelcontextprotocol/inspector http://localhost:8000/sse</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArSN0ah3QeFb6xMGRmORyQ.png" /><figcaption>MCP Server — SSE MCP Server</figcaption></figure><h4>Using Client with Weather Python Based Stdio MCP Server</h4><p>For our stdio python MCP server example, we use python weather service. We can run it using:</p><pre>python client.py &lt;path&gt;/weather.py</pre><p>When we run this command, our client connects to the weather server and we can interact with it as shown below:</p><pre>Connected to stdio MCP Server. Available tools: [&#39;get_alerts&#39;, &#39;get_forecast&#39;]<br>Type your queries or &#39;quit&#39; to exit.<br><br>Query: What&#39;s the current weather in San Fransisco?<br>Processing request of type ListToolsRequest<br>2025-04-14 10:58:19,539 - __main__ - INFO - Sending query to claude-3-5-sonnet-20241022...<br>2025-04-14 10:58:22,206 - httpx - INFO - HTTP Request: POST https://api.anthropic.com/v1/messages &quot;HTTP/1.1 200 OK&quot;<br>Processing request of type CallToolRequest<br>HTTP Request: GET https://api.weather.gov/points/37.7749,-122.4194 &quot;HTTP/1.1 200 OK&quot;<br>HTTP Request: GET https://api.weather.gov/gridpoints/MTR/85,105/forecast &quot;HTTP/1.1 200 OK&quot;<br>2025-04-14 10:58:26,510 - httpx - INFO - HTTP Request: POST https://api.anthropic.com/v1/messages &quot;HTTP/1.1 200 OK&quot;<br><br>Response: For getting the weather forecast in San Francisco, I&#39;ll need to use the get_forecast function with the city&#39;s latitude and longitude coordinates.<br><br>San Francisco&#39;s coordinates are approximately:<br>Latitude: 37.7749<br>Longitude: -122.4194<br><br>Let me get that forecast for you.<br>[Calling tool get_forecast with args {&#39;latitude&#39;: 37.7749, &#39;longitude&#39;: -122.4194}]<br>Currently in San Francisco, it&#39;s a sunny day with a temperature of 73°F. There&#39;s a light southwest wind between 2 to 8 mph. Temperatures will fall to around 67°F in the afternoon. <br><br>For tonight, it will become partly cloudy with a low of 52°F and winds around 8 mph from the west-southwest. The forecast shows a cooling trend over the next couple of days, with highs dropping to 65°F tomorrow and 63°F on Wednesday.</pre><h4>Using Client with Playwright npm Based Stdio MCP Server</h4><p>For our stdio npm server example, we use <a href="https://github.com/microsoft/playwright-mcp">microsoft/playwright-mcp</a>. We can run it using:</p><pre>python client.py @playwright/mcp@latest</pre><p>When we run this command, our client connects to the Playwright MCP server and we can interact with it as shown below:</p><pre>Connected to stdio MCP Server. Available tools: [&#39;browser_close&#39;, &#39;browser_wait&#39;, &#39;browser_file_upload&#39;, &#39;browser_install&#39;, &#39;browser_press_key&#39;, &#39;browser_navigate&#39;, &#39;browser_navigate_back&#39;, &#39;browser_navigate_forward&#39;, &#39;browser_pdf_save&#39;, &#39;browser_snapshot&#39;, &#39;browser_click&#39;, &#39;browser_drag&#39;, &#39;browser_hover&#39;, &#39;browser_type&#39;, &#39;browser_select_option&#39;, &#39;browser_take_screenshot&#39;, &#39;browser_tab_list&#39;, &#39;browser_tab_new&#39;, &#39;browser_tab_select&#39;, &#39;browser_tab_close&#39;]<br>Type your queries or &#39;quit&#39; to exit.<br><br>Query: Navigate to inflection.ai/blog and list all articles available<br><br>Response: I&#39;ll help you navigate to the Inflection AI blog and check the available articles. Let me do this step by step.<br><br>First, let&#39;s navigate to the specified URL:<br>[Calling tool browser_navigate with args {&#39;url&#39;: &#39;https://inflection.ai/blog&#39;}]<br>Based on the page snapshot, here are all the articles available on Inflection AI&#39;s blog, listed from newest to oldest:<br><br>1. &quot;Inflection Insights: a dialog with your data&quot; (Mar 28, 2025)<br>2. &quot;Porting Inflection AI&#39;s Inference Stack to Intel Gaudi: Lessons Learned&quot; (Mar 25, 2025)<br>3. &quot;Little by Little, a Little Becomes a Lot&quot; (Mar 6, 2025)<br>4. &quot;Bringing Agentic Workflows into Inflection for Enterprise&quot; (Oct 22, 2024)<br>5. &quot;Introducing Inflection for Enterprise&quot; (Oct 7, 2024)<br>6. &quot;The Future of Pi&quot; (Aug 26, 2024)<br>7. &quot;Redefining the Future of AI&quot; (May 20, 2024)<br>8. &quot;The new Inflection: An important change to how we&#39;ll work&quot; (Mar 19, 2024)<br>9. &quot;Pi: everywhere you are!&quot; (Mar 14, 2024)<br>10. &quot;Inflection-2.5: meet the world&#39;s best personal AI&quot; (Mar 7, 2024)<br>11. &quot;Pi, Now Available on Android!&quot; (Dec 7, 2023)<br>12. &quot;Inflection-2: The Next Step Up&quot; (Nov 22, 2023)<br>13. &quot;The precautionary principle: partnering with the White House on AI safety&quot; (Jul 21, 2023)<br>14. &quot;Inflection AI announces $1.3 billion of funding led by current investors, Microsoft, and NVIDIA&quot; (Jun 29, 2023)<br>15. &quot;Announcing our collaboration with NVIDIA and CoreWeave on MLPerf&quot; (Jun 27, 2023)<br>16. &quot;Inflection-1: Pi&#39;s Best-in-Class LLM&quot; (Jun 22, 2023)<br>17. &quot;Introducing Pi, Your Personal AI&quot; (May 2, 2023)<br>18. &quot;Why create personal AI?&quot; (May 2, 2023)<br>19. &quot;An Inflection point&quot; (Mar 8, 2023)<br><br>These are all the blog articles currently available on the Inflection AI website, arranged chronologically from the most recent to the oldest.</pre><h4>Using a Browser Use SSE MCP Server</h4><p>For our SSE server example, we’ll use the Browser Use <a href="https://github.com/co-browser/browser-use-mcp-server/">mcp server wrapper</a>.</p><p>Assuming you have a browser use SSE MCP server running on localhost:8000/sse, use the command below to connect the client to it:</p><pre>python client.py http://localhost:8000/sse</pre><p>Here’s what an interaction might look like:</p><pre>Connected to SSE MCP Server at http://localhost:8000/sse. <br>Available tools: [&#39;browser_use&#39;, &#39;browser_get_result&#39;]<br>Type your queries or &#39;quit&#39; to exit.<br><br>Query: Navigate to inflection.ai/blog<br><br>Response: I&#39;ll help you navigate to the Inflection AI blog using the browser tool.<br>[Calling tool browser_use with args {&#39;url&#39;: &#39;inflection.ai/blog&#39;, &#39;action&#39;: &#39;navigate&#39;}]<br>Let me check the result of the navigation:<br><br>Query: </pre><h3>Conclusion</h3><p>The Model Context Protocol provides a powerful framework for enabling AI models to interact with external tools. By supporting both stdio and SSE servers, MCP offers flexibility for both local and remote tool integration.</p><p>Our Python client implementation demonstrates how straightforward it is to create applications that leverage MCP’s capabilities. Whether you’re building local command-line utilities or web-based services, MCP provides a consistent approach to tool integration.</p><p>As the AI ecosystem continues to evolve, standards like MCP will become increasingly important for creating interoperable systems where models can seamlessly interact with a diverse array of tools and services.</p><p>By understanding the differences between stdio and SSE MCP servers and how to build clients for both, you now have the foundation to develop sophisticated AI applications that can leverage external capabilities through a standardized protocol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=773b187aeaed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LangChain Agents to Invoke a Robotics Process Automation (RPA): A Quick Intro]]></title>
            <link>https://thesof.medium.com/using-langchain-agents-to-invoke-a-robotics-process-automation-rpa-a-quick-intro-716a5bb711ae?source=rss-652fc735ad42------2</link>
            <guid isPermaLink="false">https://medium.com/p/716a5bb711ae</guid>
            <category><![CDATA[uipath]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rap]]></category>
            <dc:creator><![CDATA[Sofiane Ghadab]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 05:35:06 GMT</pubDate>
            <atom:updated>2024-10-16T05:35:06.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nPs3lyAAQxRopk_9Ya6dcQ.png" /></figure><p>For those who have been involved in Robotic Process Automation (RPA) for a while, recent advances in artificial intelligence are an exciting development. RPA has helped countless companies, particularly those with legacy or disconnected systems, to innovate and automate their processes efficiently and cost-effectively. However, RPA has historically struggled with processes that involve unstructured data, such as free-form text fields, email bodies, or documents without a consistent format. While Intelligent Document Processing (IDP) solutions like AWS Textract, Azure Form Recognizer, UiPath Document Understanding…etc. have helped address some of these challenges, unstructured and highly variable data remains a sticky problem.</p><p>This is where large language models (LLMs) shine. LLMs excel at processing unstructured data, extracting intent, and identifying relevant data points. Combining Generative AI with RPA naturally expands the scope of what can be automated in a reliable and cost-effective way.</p><p>RPA professionals are likely already familiar with invoking LLMs within workflows, leveraging APIs provided by LLM vendors or high-level connectors provided by RPA platforms like UiPath. The future of automation, however, is increasingly agent-driven, with AI agents expected to not only interact with but also orchestrate complex workflows. Agents are powerful because they can leverage custom tools to gather information or perform actions that they can’t handle on their own. These tools can even include RPA processes.</p><p>While researching this topic, I found limited resources on how AI agents could be used to invoke RPA automations directly. Therefore, I decided to share my learnings in this introduction, hoping to save others time and help them avoid some of the mistakes I encountered while exploring this integration.</p><p>In this article, I’ll show how to use a LangChain agent to invoke a <a href="https://www.uipath.com/">UiPath</a> automation process. The same pattern can be replicated for other RPA tools like Blue Prism, Automation Anywhere, or Microsoft Power Automate. The article is organized into two parts: Part 1 will guide you through building an agent that uses a custom tool, and Part 2 will explain how to configure that tool to invoke an RPA automation process. The potential use cases for this are immense, particularly in enterprises with legacy systems lacking APIs or where direct access to back-end databases is not feasible. RPA enables AI agents to interact with these systems via their GUI, just as a human would.</p><h3>Part 1: Building Agents and Custom Tools Using LangChain</h3><p>LangChain supports different types of agents, such as <strong><em>Zero-Shot ReAct</em></strong>, <strong><em>Structured Input ReAct</em></strong>, <strong><em>Conversational</em></strong>, <strong><em>Self-Ask with Search</em></strong>, <strong>ReAct Document Store</strong>…etc. In this example, we use a <strong><em>PlanAndExecute</em></strong> agent with custom tools. <strong><em>PlanAndExecute</em></strong> agents, as their name indicates, plan their actions before executing individual tasks, making them suitable for orchestrating complex workflows. The example is inspired by Mehul Gupta’s book: “<a href="https://read.amazon.com/kp/embed?asin=B0CTHQHT25&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_80YF76ZG58G0D395TEZS&amp;tag=atlas06a-20">LangChain in Your Pocket</a>,” which explains LangChain concepts succinctly for newcomers.</p><h4>Steps to Get Started:</h4><p>Step 1: Set Up Your Python Virtual Environment (optional step)</p><p>Open a terminal window, navigate to your project folder, and use the command below to create a new virtual environment:</p><pre>python -m venv .venv</pre><p>Activate the environment using the command:</p><p>Windows:</p><pre>.venv\Scripts\activate</pre><p>MacOS:</p><pre>source .venv/bin/activate</pre><p>To deactivate the environment, use:</p><pre>deactivate</pre><p>Step 2: Install the Required Packages</p><p>We need the following packages:<br><em>- pydantic<br>- langchain<br>- langchain-community<br>- langchain-experimental<br>- python-dotenv</em></p><p>Install them with:</p><pre>pip install pydantic langchain langchain-community langchain-experimental python-dotenv</pre><p>Step 3: Set Up Custom Tools and AI Agent</p><p>For every custom tool, we need two classes:<br>1. A class to define input<br>2. A class to call the function as a tool</p><p>Here is the code:</p><pre>from typing import Type<br>from pydantic import BaseModel, Field<br>from langchain.tools import BaseTool<br>from langchain.agents.tools import tool<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner<br><br># Simulated function to invoke UiPath automation<br>def invoke_UiPath_Automation_GetMemberInfo(SSN: str) -&gt; str:<br>    if SSN == &quot;123-45-6789&quot;:<br>        return &quot;{&#39;Hits&#39;: 1, {&#39;Name&#39;: &#39;John Doe&#39;, &#39;Gender&#39;: &#39;M&#39;, &#39;DOB&#39;: &#39;01/01/1900&#39;}}&quot;<br>    else:<br>        return &quot;{&#39;Hits&#39;: 0}&quot;<br><br># Pydantic model to validate input<br>class Get_Automation_GetMemberInfo_Input(BaseModel):<br>    &#39;&#39;&#39;Input for automation&#39;&#39;&#39;<br>    SSN: str = Field(description=&quot;SSN for member in the following format xxx-xx-xxxx&quot;)<br><br># Custom tool to interact with the function invoking the automation<br>class Invoke_UiPath_Automation_GetMemberInfo(BaseTool):<br>    name: str = &quot;invoke_uipath_automation&quot;<br>    description: str = &quot;&quot;&quot;<br>        Useful to get member info based on their SSN.<br>        Mandatory input format is SSN in the following format xxx-xx-xxxx.<br>        &quot;&quot;&quot;<br>    args_schema: Type[BaseModel] = Get_Automation_GetMemberInfo_Input<br><br>    def _run(self, SSN: str) -&gt; str:<br>        member_info = invoke_UiPath_Automation_GetMemberInfo(SSN)<br>        return member_info<br>    <br>    def _arun(self, SSN: str):<br>        raise NotImplementedError(&quot;This tool doesn&#39;t support async&quot;)<br><br><br># Set up the agent<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)<br>tools = [Invoke_UiPath_Automation_GetMemberInfo()]<br><br>planner = load_chat_planner(llm)<br>executor = load_agent_executor(llm, tools, verbose=True)<br>agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)<br><br># Provide the query and run the agent<br>result = agent.run(&#39;Get me the member information for member whose SSN is 123-45-6789.&#39;)<br>print(f&quot;[{result}]&quot;)</pre><p>Explanation of the Code:</p><p>1. <em>invoke_UiPath_Automation_GetMemberInfo(SSN: str)</em>: This is the custom tool that the agent will use to retrieve a member’s information based on a provided Social Security Number (SSN). It takes an SSN as input and returns a JSON-like string simulating the result. In Part 2, we’ll update this function to call an actual UiPath automation process deployed on an Orchestrator tenant.</p><p>2. <em>class Get_Automation_GetMemberInfo_Input(BaseModel)</em>: Inherits from Pydantic’s `BaseModel` and defines the input that the automation function requires. Using Pydantic ensures the input is validated at runtime.</p><p>3. <em>class Invoke_UiPath_Automation_GetMemberInfo(BaseTool)</em>: Inherits from `BaseTool` and provides a description of the tool. The description helps the agent understand what the tool is for and when to use it.</p><p>4. <em>Setting up the Agent</em>: We use a GPT-3.5 Turbo model from OpenAI, but any other LLM (local or remote) can be used. The tools are defined and loaded, and the agent is set up to execute the required task.</p><p>5. Running the Agent: Finally, we provide a query and run the agent, which retrieves and prints the member information.</p><pre>&gt; Entering new PlanAndExecute chain...                                                                                                            <br>steps=[Step(value=&#39;Access the database or system where the member information is stored.&#39;), Step(value=&#39;Search for the member with SSN 123-45-6789<br>.&#39;), Step(value=&#39;Retrieve all relevant information associated with the member.&#39;), Step(value=&#39;Display the member information to the user.&#39;), Step(<br>value=&#39;End process.\nGiven the above steps taken, please provide the member information for the member whose SSN is 123-45-6789. \n&#39;)]            <br>                                                                                                                                                  <br>&gt; Entering new AgentExecutor chain...                                                                                                             <br>Thought: I need to use the UiPath automation tool to retrieve member information based on their SSN to help the user access the database.         <br>                                                                                                                                                  <br>Action:                                                                                                                                           <br>```                                                                                                                                               <br>{                                                                                                                                                 <br>  &quot;action&quot;: &quot;invoke_uipath_automation&quot;,                                                                                                           <br>  &quot;action_input&quot;: {&quot;SSN&quot;: &quot;123-45-6789&quot;}                                                                                                          <br>}                                                                                                                                                 <br>```                                                                                                                                               <br>Observation: {&#39;Hits&#39;: 1, {&#39;Name&#39;: &#39;John Doe&#39;, &#39;Gender&#39;: &#39;M&#39;, &#39;DOB&#39;: &#39;01/01/1900&#39;}}                                                                <br>Thought:Thought: Now that I have successfully retrieved the member information for SSN &quot;123-45-6789,&quot; I can provide it to the user.<br>....</pre><p>Note: The code can be further simplified by using the `<a href="http://twitter.com/tool">@tool</a>` decorator as shown below, but the Pydantic-based approach is preferable for validating inputs to ensure that they meet the requirements of the automation.</p><pre>from pydantic import BaseModel, Field<br>from langchain.tools import BaseTool<br>from langchain.agents import AgentType, initialize_agent<br>from langchain.agents.tools import tool<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner<br><br># Simulated function to invoke UiPath automation<br>@tool<br>def invoke_UiPath_Automation_GetMemberInfo(SSN: str) -&gt; str:<br>    &quot;&quot;&quot;Useful to get member info based on their SSN.<br>        Mandatory input format is SSN in the following format xxx-xx-xxxx.&quot;&quot;&quot;<br>    <br>    if SSN == &quot;123-45-6789&quot;:<br>        return &quot;{&#39;Hits&#39;: 1, {&#39;Name&#39;: &#39;John Doe&#39;, &#39;Gender&#39;: &#39;M&#39;, &#39;DOB&#39;: &#39;01/01/1900&#39;}}&quot;<br>    else:<br>        return &quot;{&#39;Hits&#39;: 0}&quot;<br><br><br># Set up the agent<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)<br>tools = [invoke_UiPath_Automation_GetMemberInfo]<br><br>planner = load_chat_planner(llm)<br>executor = load_agent_executor(llm, tools, verbose=True)<br>agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)<br><br># Provide the query and run the agent<br>result = agent.run(&#39;Get me the member information for member whose SSN is 123-45-6789&#39;)<br><br>print(f&quot;[{result}]&quot;)</pre><h3>Part 2: Invoking a Real UiPath Automation Through Orchestrator API</h3><p>In Part 2, we outline the steps needed to replace the simulated function with a real UiPath automation call using the Orchestrator API. This involves setting up an external application, configuring the correct API scopes, and authenticating via the UiPath Orchestrator API.</p><h4>Administrator Tasks: Setting Up an External Application</h4><p>To use the API to start a UiPath job, an “External Application” must be configured through the UiPath Admin Dashboard. Here are the steps:</p><ol><li><strong>Log in to the UiPath Admin Dashboard</strong>: Have your UiPath Automation Cloud administrator log in.</li><li><strong>Navigate to External Applications</strong>: Under the Admin Dashboard, select “External Applications.”</li><li><strong>Add a New Application</strong>: Click on “+ Add Application.”<br>Application Name: Provide a name for the application.<br>Application Type: Select “Confidential Application.”<br>Resources: Click “+ Add Scopes.”<br>Resource: Select “Orchestrator API Access.”<br> - Application Scopes: Add <strong><em>OR.Jobs, OR.Execution, OR.Folders</em></strong>.<br> - Redirect URL: Leave this blank (not needed for Confidential Application).</li><li><strong>Save the Application</strong>: Once saved, a pop-up with the App ID and App Secret will be displayed. The administrator needs to save these credentials and provide them to the developer.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*ZCAFqAQE1gYsL3aW0lJGFg.png" /><figcaption>Add an External Application</figcaption></figure><p><strong><em>Note:</em></strong> It is important to select the correct scopes to avoid any permission issues when triggering an automation.</p><h4>Developer Tasks: Starting a Job Through API</h4><p>The developer needs to use several UiPath Orchestrator API endpoints to:<br>1. Authenticate and get an access token.<br>2. Retrieve the Organization Unit ID (Folder ID).<br>3. Get the release key for the target process.<br>4. Start the job using the API.<br>5. Check the job status until completion.</p><p>The complete list of available API for UiPath Orchestrator can be visualized (and tested) through <em>Swagger</em> using the link</p><p><a href="https://cloud.uipath.com/%7borganization%7d/%7btenant%7d/orchestrator_/swagger/index.html#/Jobs/Jobs_StartJobs">https://cloud.uipath.com/{organization}/{tenant}/orchestrator_/swagger/index.html</a></p><p>It’s probably a good idea to store all your sensitive information like Client ID, Client Secret, Scope, Organization name, Tenant name…etc. as environment variables, or inside an environment configuration file added to the root folder of your Python project. Here, I chose the latter and I added a <strong><em>.env</em></strong> file to my project with the entries below</p><pre>UIPATH_CLIENT_ID=&lt;Your Client ID&gt;<br>UIPATH_CLIENT_SECRET=&lt;Your Client Secret&gt;<br>UIPATH_SCOPE=OR.Jobs OR.Execution OR.Folders<br>UIPATH_TENANT_NAME=&lt;Your Orchestrator Tenant&gt;<br>UIPATH_ORGANIZATION=&lt;Your Orchestrator Organization&gt;<br>UIPATH_FOLDER_PATH=&lt;The path to the Orchestrator folder for your target process&gt;<br>UIPATH_PROCESS_NAME=&lt;Your process name (as it appears in Orchestrator)&gt;</pre><p>Step 1: Authenticate and Get Access Token</p><p>Use the https://cloud.uipath.com/identity_/connect/token endpoint to authenticate and get an access token. This token will be used for all subsequent API requests.</p><pre>    # Step 1: Authenticate and get access token<br>    auth_url = &#39;https://cloud.uipath.com/identity_/connect/token&#39;<br>    auth_payload = f&quot;grant_type=client_credentials&amp;client_id={client_id}&amp;client_secret={client_secret}&amp;scope={scope}&quot;<br><br>    auth_headers = {<br>        &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>    }<br><br>    auth_response = requests.request(&quot;POST&quot;, auth_url, headers=auth_headers, data=auth_payload)<br>    auth_response.raise_for_status()<br>    access_token = auth_response.json()[&#39;access_token&#39;]</pre><p>Step 2: Retrieve the Organization Unit ID (Folder ID)</p><p>Use the https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Folders endpoint to retrieve the Organization Unit ID for your target automation process.</p><pre>    # Step 2: Get Organization Unit ID (Folder ID) for target automation process<br>    folders_url = f&quot;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Folders&quot;<br>    params = {<br>        &#39;$filter&#39;: f&quot;((contains(FullyQualifiedName,&#39;{folder_path}&#39;)))&quot;<br>    }<br>    headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>    }<br>    payload = {}<br>    <br>    response = requests.request(&quot;GET&quot;, folders_url, params=params, headers=headers, data=payload)<br>    response.raise_for_status()<br>    folders = response.json()[&#39;value&#39;]<br>    if not folders:<br>        raise Exception(f&quot;No folders found for path: {folder_path}&quot;)<br>    organization_unit_id = folders[0][&#39;Id&#39;]</pre><p>Step 3: Get the Release Key for the Target Process</p><p>Use the https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Releases/UiPath.Server.Configuration.OData.ListReleases endpoint to get the release key for your target automation process.</p><pre>    # Step 3: Get Release Key for target automation process<br>    releases_url = f&quot;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Releases/UiPath.Server.Configuration.OData.ListReleases&quot;<br>                           <br>    params = {<br>        &#39;$filter&#39;: f&quot;((contains(ProcessKey,&#39;{process_key}&#39;)))&quot;<br>    }<br>    headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>         &#39;X-UIPATH-OrganizationUnitId&#39;: f&#39;{organizationUnitId}&#39;<br>    }<br>    payload = {}<br>    <br>    response = requests.request(&quot;GET&quot;, releases_url, params=params, headers=headers, data=payload)<br>    response.raise_for_status()<br>    releases = response.json()[&#39;value&#39;]<br>    if not releases:<br>        raise Exception(f&quot;No releases found for process key: {process_key}&quot;)<br>    release_key = releases[0][&#39;Key&#39;]</pre><p>Step 4: Start the Job Using the API</p><p>Use the https://cloud.uipath.com/{organization}/{tenant}/orchestrator_/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs endpoint to start the job.</p><pre>    # Step 4: Start the job<br>    start_job_url_template = &#39;https://cloud.uipath.com/{organization}/{tenant}/orchestrator_/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs&#39;<br>    start_job_url = start_job_url_template.format(organization=organization, tenant=tenant_name)<br>    start_job_headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>         &#39;X-UIPATH-OrganizationUnitId&#39;: f&#39;{organizationUnitId}&#39;,<br>         &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br><br>    start_job_payload = json.dumps(<br>        {<br>            &quot;startInfo&quot;: {<br>                &quot;ReleaseKey&quot;: f&quot;{release_key}&quot;,<br>                &quot;RobotIds&quot;: [],<br>                &quot;JobsCount&quot;: 1,<br>                &quot;JobPriority&quot;: &quot;Normal&quot;,<br>                &quot;Strategy&quot;: &quot;ModernJobsCount&quot;,<br>                &quot;InputArguments&quot;: f&quot;{kwargs}&quot;<br>            }<br>        }<br>    )<br><br>    start_job_response = requests.request(&quot;POST&quot;, start_job_url, headers=start_job_headers, data=start_job_payload)<br><br>    start_job_response.raise_for_status()<br>    job_info = start_job_response.json()<br><br>    # Get the job ID<br>    job_id = job_info[&#39;value&#39;][0][&#39;Id&#39;]</pre><p>Step 5: Check the Job Status Until Completion</p><p>Use the https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Jobs({job_id}) endpoint to check the status of the job until it is completed.</p><pre># Step 5: Poll the job status until completion<br>jobs_url = f&quot;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Jobs({job_id})&quot;<br>job_status = &#39;Pending&#39;<br>while job_status not in [&#39;Successful&#39;, &#39;Faulted&#39;, &#39;Stopped&#39;]:<br>    time.sleep(5)  # Wait for 5 seconds before checking the status again<br>    headers = {<br>        &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>        &#39;X-UIPATH-OrganizationUnitId&#39;: str(organization_unit_id)<br>    }<br>    response = requests.request(&quot;GET&quot;, jobs_url, headers=headers)<br>    response.raise_for_status()<br>    job = response.json()<br>    job_status = job[&#39;State&#39;]<br>    job_output = job.get(&#39;OutputArguments&#39;, None)<br>    if job_status == &#39;Successful&#39;:<br>        print(&quot;Job completed successfully.&quot;)<br>        return job_output<br>    elif job_status in [&#39;Faulted&#39;, &#39;Stopped&#39;]:<br>        raise Exception(f&quot;Job failed with status: {job_status}&quot;)</pre><p>Putting it all together and updating the code in Part 1:</p><pre>from typing import Type<br>from pydantic import BaseModel, Field<br>from langchain.tools import BaseTool<br>from langchain.agents.tools import tool<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner<br>import requests<br>import time<br>import json<br>from typing import Tuple<br>import os<br>from dotenv import load_dotenv<br><br># Load Environment variables from .env file<br>load_dotenv()<br><br># Function to invoke UiPath automation via UiPath Orchestrator API<br>def invoke_UiPath_Automation(process_name: str, **kwargs) -&gt; str:<br>    &#39;&#39;&#39; Invokes UiPath automation process_name with arguments defined kwargs &#39;&#39;&#39;<br>    <br>    process_key = process_name  # The name of your process as defined in UiPath Orchestrator<br>    # Read environment variables for sensitive information<br>    client_id = os.environ.get(&#39;UIPATH_CLIENT_ID&#39;)<br>    client_secret= os.environ.get(&#39;UIPATH_CLIENT_SECRET&#39;)<br>    scope= os.environ.get(&#39;UIPATH_SCOPE&#39;)<br>    tenant_name = os.environ.get(&#39;UIPATH_TENANT_NAME&#39;)<br>    organization = os.environ.get(&#39;UIPATH_ORGANIZATION&#39;)<br>    folder_path = os.environ.get(&#39;UIPATH_FOLDER_PATH&#39;)<br>    <br>    if not all([client_id, client_secret, tenant_name, organization, folder_path]):<br>        raise ValueError(&quot;Please set UIPATH_CLIENT_ID, UIPATH_SECRET, UIPATH_SCOPE, UIPATH_TENANT_NAME, UIPATH_ORGANIZATION, and UIPATH_FOLDER_PATH environment variables.&quot;)<br><br>    # Step 1: Authenticate and get access token<br>    access_token = get_access_token(client_id, client_secret, scope)<br>    <br>    # Step 2: Get OrganizationUnitId (Folder ID) for target automation process<br>    organizationUnitId = get_OrganizationUnitId(access_token, tenant_name, organization, folder_path)<br>    <br>    # Step 3: Get Release Key for target automation process<br>    release_key = get_release_key(access_token, tenant_name, organization, process_key, organizationUnitId)<br><br>    # Step 4: Start the job<br>    start_job_url_template = &#39;https://cloud.uipath.com/{organization}/{tenant}/orchestrator_/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs&#39;<br>    start_job_url = start_job_url_template.format(organization=organization, tenant=tenant_name)<br>    start_job_headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>         &#39;X-UIPATH-OrganizationUnitId&#39;: f&#39;{organizationUnitId}&#39;,<br>         &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br><br>    start_job_payload = json.dumps(<br>        {<br>            &quot;startInfo&quot;: {<br>                &quot;ReleaseKey&quot;: f&quot;{release_key}&quot;,<br>                &quot;RobotIds&quot;: [],<br>                &quot;JobsCount&quot;: 1,<br>                &quot;JobPriority&quot;: &quot;Normal&quot;,<br>                &quot;Strategy&quot;: &quot;ModernJobsCount&quot;,<br>                &quot;InputArguments&quot;: f&quot;{kwargs}&quot;<br>            }<br>        }<br>    )<br><br>    start_job_response = requests.request(&quot;POST&quot;, start_job_url, headers=start_job_headers, data=start_job_payload)<br><br>    start_job_response.raise_for_status()<br>    job_info = start_job_response.json()<br><br>    # Get the job ID<br>    job_id = job_info[&#39;value&#39;][0][&#39;Id&#39;]<br><br>    # Step 5: Poll the job status until completion<br>    job_status = &#39;Pending&#39;<br>    job_output = None<br>    while job_status not in [&#39;Successful&#39;, &#39;Faulted&#39;, &#39;Stopped&#39;]:<br>        time.sleep(5)  # Wait for 5 seconds before checking the status again<br>        job_status, job_output = get_job_status(access_token, tenant_name, organization, job_id, organizationUnitId)<br>        if job_status == &#39;Successful&#39;:<br>            # Retrieve output arguments<br>            return job_output<br>        elif job_status in [&#39;Faulted&#39;, &#39;Stopped&#39;]:<br>            raise Exception(f&quot;Job failed with status: {job_status}&quot;)<br><br>    raise Exception(&quot;Job did not complete successfully.&quot;)<br><br>def get_access_token(client_id: str, client_secret: str, scope: str) -&gt; str:<br>    &#39;&#39;&#39; Function to authenticate and get authorization access token&#39;&#39;&#39;<br><br>    auth_url = &#39;https://cloud.uipath.com/identity_/connect/token&#39;<br>    auth_payload = f&quot;grant_type=client_credentials&amp;client_id={client_id}&amp;client_secret={client_secret}&amp;scope={scope}&quot;<br><br>    auth_headers = {<br>        &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>    }<br><br>    auth_response = requests.request(&quot;POST&quot;, auth_url, headers=auth_headers, data=auth_payload)<br>    auth_response.raise_for_status()<br>    access_token = auth_response.json()[&#39;access_token&#39;]<br>    return access_token<br>    <br>def get_OrganizationUnitId(access_token: str, tenant_name: str, organization: str, folder_path: str) -&gt; int:<br>    &#39;&#39;&#39; Function to get OrganizationUnitId (Folder ID) for Orchestrator folder folder_path&#39;&#39;&#39;<br><br>    folders_url = f&quot;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Folders&quot;<br>    params = {<br>        &#39;$filter&#39;: f&quot;((contains(FullyQualifiedName,&#39;{folder_path}&#39;)))&quot;<br>    }<br>    headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>    }<br>    payload = {}<br>    <br>    response = requests.request(&quot;GET&quot;, folders_url, params=params, headers=headers, data=payload)<br>    response.raise_for_status()<br>    folders = response.json()[&#39;value&#39;]<br>    if not folders:<br>        raise Exception(f&quot;No folders found for path: {folder_path}&quot;)<br>    return folders[0][&#39;Id&#39;]<br><br>def get_release_key(access_token: str, tenant_name: str, organization: str, process_key: str, organizationUnitId: int) -&gt; str:<br>    &#39;&#39;&#39; Function to get Release Key for target automation process process_key&#39;&#39;&#39;<br>    releases_url = f&quot;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Releases/UiPath.Server.Configuration.OData.ListReleases&quot;<br>                           <br>    params = {<br>        &#39;$filter&#39;: f&quot;((contains(ProcessKey,&#39;{process_key}&#39;)))&quot;<br>    }<br>    headers = {<br>         &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>         &#39;X-UIPATH-OrganizationUnitId&#39;: f&#39;{organizationUnitId}&#39;<br>    }<br>    payload = {}<br>    <br>    response = requests.request(&quot;GET&quot;, releases_url, params=params, headers=headers, data=payload)<br>    response.raise_for_status()<br>    releases = response.json()[&#39;value&#39;]<br>    if not releases:<br>        raise Exception(f&quot;No releases found for process key: {process_key}&quot;)<br>    return releases[0][&#39;Key&#39;]<br><br>def get_job_status(access_token: str, tenant_name: str, organization, job_id: int, organizationUnitId: int) -&gt; Tuple[str,str]:<br>    # Function to get the status of the job<br>    jobs_url = f&#39;https://cloud.uipath.com/{organization}/{tenant_name}/orchestrator_/odata/Jobs({job_id})&#39;<br>    headers = {<br>        &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>        &#39;X-UIPATH-OrganizationUnitId&#39;: f&#39;{organizationUnitId}&#39;<br>    }<br>    <br>    response = requests.request(&quot;GET&quot;, jobs_url, headers=headers)<br>    response.raise_for_status()<br>    job = response.json()<br>    job_status = job[&#39;State&#39;]<br>    job_output = job.get(&#39;OutputArguments&#39;, None)<br>    return job_status, job_output<br><br># Pydantic model to validate input<br>class Get_Automation_GetMemberInfo_Input(BaseModel):<br>    &#39;&#39;&#39;Input for automation&#39;&#39;&#39;<br>    SSN: str = Field(description=&quot;SSN for member in the following format xxx-xx-xxxx&quot;)<br><br># Custom tool to interact with the function invoking the automation<br>class Invoke_UiPath_Automation_GetMember(BaseTool):<br>    name: str = &quot;invoke_uipath_automation&quot;<br>    description: str = &quot;&quot;&quot;<br>        Useful to get member info based on their SSN.<br>        Mandatory input format is SSN in the following format xxx-xx-xxxx.<br>        &quot;&quot;&quot;<br>    args_schema: Type[BaseModel] = Get_Automation_GetMemberInfo_Input<br><br>    def _run(self, SSN: str) -&gt; str:<br>        member_info = invoke_UiPath_Automation(&quot;Get_Member_info&quot;,SSN=SSN)<br>        return member_info<br>    <br>    def _arun(self, SSN: str):<br>        raise NotImplementedError(&quot;This tool doesn&#39;t support async&quot;)<br><br># Set up the agent<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)<br>tools = [Invoke_UiPath_Automation_GetMember()]<br><br>planner = load_chat_planner(llm)<br>executor = load_agent_executor(llm, tools, verbose=True)<br>agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)<br><br># Provide the query and run the agent<br>result = agent.run(&#39;Get me the member information for member whose SSN is 222-22-2222.&#39;)<br>print(f&quot;[{result}]&quot;)</pre><p><strong>Note:</strong> Unlike in part 1, I’ve made the function to invoke the UiPath automation generic. It can take any automation process (name) with any input arguments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716a5bb711ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>