Conversational Agent

                      Conversational Agent



I'd like to create a simple conversational agent on GCP that leverages the mcp server that was created 


To build a conversational AI agent that orchestrates tools from your sec-agent-mcp Cloud Run deployment, the standard production design uses a LangGraph ReAct Agent powered by gemini-2.5-flash via the langchain-mcp-adapters library.

This setup allows Gemini to dynamically inspect your remote MCP server's JSON-RPC tool schemas (lookup_cik, search_securities, search_filing_vectors) over SSE and invoke them in a conversational loop.

Install Dependencies in Cloud Shell

In your local environment or Cloud Shell, install the MCP bridge and Gemini LangChain integration:



requirements.txt

langchain-mcp-adapters>=0.1.0

langgraph>=0.2.0

langchain-google-genai>=2.0.0

google-genai>=0.3.0

python-dotenv>=1.0.0


pip install -r requirements.txt


Create agent.py

Create a script named agent.py in your project folder. It connects to [https://sec-agent-mcp-apkiqkbzyq-ue.a.run.app/sse](https://sec-agent-mcp-apkiqkbzyq-ue.a.run.app/sse), fetches your tools dynamically, and initializes the interactive agent loop:



import os

import warnings

import asyncio


# Suppress LangChain / LangGraph deprecation & serialization warnings

warnings.filterwarnings("ignore", category=UserWarning)

warnings.filterwarnings("ignore", category=DeprecationWarning)


from langchain_mcp_adapters.client import MultiServerMCPClient

from langchain.agents import create_agent

from langchain_google_genai import ChatGoogleGenerativeAI


CLOUD_RUN_SSE_URL = "https://sec-agent-mcp-apkiqkbzyq-ue.a.run.app/sse"


async def run_conversational_agent():

    api_key = os.environ.get("GEMINI_API_KEY")

    if not api_key:

        raise ValueError("Please set your GEMINI_API_KEY environment variable.")


    print(f"Connecting agent to MCP Server at {CLOUD_RUN_SSE_URL}...")


    # Initialize connection with timeouts for Cloud Run latency

    client = MultiServerMCPClient({

        "sec_tools": {

            "transport": "sse",

            "url": CLOUD_RUN_SSE_URL,

            "timeout": 30.0,

            "sse_read_timeout": 300.0

        }

    })


    # Automatically load remote tools exposed by FastMCP

    tools = await client.get_tools()

    print(f"Discovered {len(tools)} remote MCP tools: {[t.name for t in tools]}")


    # Initialize Gemini 2.5 Flash

    llm = ChatGoogleGenerativeAI(

        model="gemini-2.5-flash",

        google_api_key=api_key,

        temperature=0.2

    )


    system_prompt = (

        "You are an expert SEC EDGAR Financial Research Assistant. "

        "Use the available MCP tools to lookup company CIKs, search securities master records, "

        "and retrieve vector search filing chunks before answering quantitative finance questions."

    )


    # Replaced create_react_agent with create_agent and system_prompt

    agent = create_agent(llm, tools, system_prompt=system_prompt)


    print("\n--- SEC EDGAR Conversational Agent Ready ---")

    print("Type your financial query below (or type 'exit' to quit):\n")


    conversation_history = []


    while True:

        try:

            user_input = input("User > ")

        except (KeyboardInterrupt, EOFError):

            break


        if user_input.strip().lower() in ["exit", "quit"]:

            break


        if not user_input.strip():

            continue


        conversation_history.append(("user", user_input))


        response = await agent.ainvoke({"messages": conversation_history})


        # Process message response cleanly

        last_msg = response["messages"][-1]

        final_content = last_msg.content if isinstance(last_msg.content, str) else str(last_msg.content)

       

        conversation_history.append(("assistant", final_content))


        print(f"\nAgent > {final_content}\n")


if __name__ == "__main__":

    asyncio.run(run_conversational_agent())


Run the Conversational Agent

Execute agent.py in your terminal:


$ python agent.py

/home/john_iacovacci1/.local/lib/python3.12/site-packages/langgraph/checkpoint/serde/encrypted.py:5: LangChainPendingDeprecationWarning: The default value of `allowed_objects` will change in a future version. Pass an explicit value (e.g., allowed_objects='messages' or allowed_objects='core') to suppress this warning.

  from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer

Connecting agent to MCP Server at https://sec-agent-mcp-apkiqkbzyq-ue.a.run.app/sse...

Discovered 3 remote MCP tools: ['lookup_cik', 'search_securities', 'search_filing_vectors']


--- SEC EDGAR Conversational Agent Ready ---

Type your financial query below (or type 'exit' to quit):


User > Find the CIK for Apple and check if Microsoft is listed in our securities table.


Agent > The CIK for Apple Inc. is 0000320193. Yes, Microsoft is listed in the securities table with the ticker MSFT, FIGI BBG000BPH459, and is a Common Stock in the Equity market sector.


User > 


No comments:

Post a Comment

UCONN Stamford Fintech Student Showcase December 2nd 6:00pm-8:00pm Main auditorium

  Professors Wei Chen and David Wanik will have teams present at the Fintech Showcase on December 2 nd from 6:00pm to 8:00pm in the main au...