Skip to content
Back to search

a2a-mcp-tutorial

A tutorial on how to use Model Context Protocol by Anthropic and Agent2Agent Protocol by Google

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/tsadoq--a2a-mcp-tutorial/badge.svg)](/listings/tsadoq--a2a-mcp-tutorial)

HTML

<a href="/listings/tsadoq--a2a-mcp-tutorial"><img src="/api/listings/tsadoq--a2a-mcp-tutorial/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,202 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Agent2Agent and MCP: An End-to-End Tutorial for a complete Agentic Pipeline
  2. ## Introduction
  3. In the fast-moving world of agentic AI, two open protocols quietly solve the headaches that used to keep multi-agent projects from ever leaving the lab.
  4. A few months ago, Anthropic introduced [Model Context Protocol (MCP)](https://www.anthropic.com/news/model-context-protocol): A reliable access to the data and tools an agent needs once the conversation begins. Anthropic describes MCP as a USB-C port for language models—a single, well-defined connector that lets you plug the same model into GitHub, a Postgres database, or a custom knowledge base without rewriting the integration each time. By standardizing the way hosts, clients, and servers exchange "Tools," "resources," and "prompts," MCP turns context into something the model can count on rather than something developers keep stitching together ad hoc.  
  5. Agent2Agent (A2A), a new protocol by Google, tackles another obstacle: getting autonomous agents—often built on different frameworks and hosted in different places—to understand one another. Instead of brittle, one-off bridges, A2A gives every agent a tiny "agent card" that advertises its skills and an HTTP interface that lets other agents negotiate tasks, stream intermediate results, and hand over artifacts. Google started the project to give agents a common language regardless of vendor, and the open-source spec already shows how discovery, task life-cycle updates, and secure push notifications can work out of the box. 
  6. With A2A handling how agents talk to one another and MCP handling how they tap into the outside world, you end up with small, focused agents who can coordinate fluently and still see the bigger picture—an architecture that feels less like a collection of scripts and more like a cooperative workforce.
  7. ## The Structure of this Tutorial
  8. This tutorial will build a complete agentic pipeline using Agent2Agent and MCP. First, we will create and test a couple of simple MCP servers. Then, we will create a simple agent that uses MCP to get information. Finally, we will have a whole crew of agents that uses Agent2Agent to coordinate with each other while using MCP to get information.
  9. For the sake of simplicity, we will use elementary agents that have access to single MCPs and MCPs that perform easy operations like fetching data from an API or searching the web.
  10. We imagine we want to create a team of agents able to make simple reports about American Companies; in particular, we want to be able to ask questions such as "What is the price of the stocks of the top 10 companies in the S&P 500?" or "What are the top 5 producers of lumber in the US"?
  11. ## Note on the Code
  12. The code for this tutorial is available on [GitHub](https://github.com/Tsadoq/a2a-mcp-tutorial). You should clone the repository, run the code locally, play around with it, and even modify it. This tutorial has been created by starting from two sources:
  13. - [Agent2Agent Tutorial](https://github.com/google/A2A)
  14. - [MCP Tutorial](https://modelcontextprotocol.io/quickstart/server)
  15. While the MCP documentation was terrific, the Google Agent2Agent repository had multiple issues and was not working as expected. As a consequence, I heavily modified the code provided.
  16. ### How to run it
  17. [uv by Astral](https://docs.astral.sh/uv/) was used as a Python package and project manager. You can clone the repo, run `uv sync`, and then run whatever you need.
  18. ![mcp_rein](https://github.com/user-attachments/assets/c8520cc2-69a1-4bfa-81e2-3b2d18b977c8)
  19. # MCP Servers
  20. Given our objective, we first define two services:
  21. - A crawler able to search on Google and read web pages
  22. - A stock retriever, able to get the price of a stock at a particular time and other helpful info
  23. ## The Stock Retriever Service
  24. We define a simple stock retriever service using FinHub APIs. The retriever will return a stock's current price, min, max opening, and closing price (IMPORTANT: if you use the free version of the APIs, only the US market can be queried) with one endpoint and the stock symbol with the other.
  25. ```python
  26. class FinHubService:
  27. def __init__(self):
  28. """
  29. Initializes the finhubservice.
  30. """
  31. self.client = finnhub.Client(api_key=os.getenv("FINNHUB_API_KEY"))
  32. def get_symbol_from_query(self, query: str) -> Dict[str,Any]:
  33. """
  34. Given a query (e.g. name of a company) returns a dictionary with info. Use only if you have no idea about the symbol.
  35. :param query: name of company
  36. :return: dictionary with the response to the query
  37. """
  38. return self.client.symbol_lookup(
  39. query=query,
  40. )
  41. def get_price_of_stock(self, symbol: str) -> Dict[str,Any]:
  42. """
  43. Given the symbol of a certain strock, returns the live info about it.
  44. :param symbol: The symbol of a stock, e.g. AAPL
  45. :return: a dictionary containing the current_price, change, %change, day high, low, opening and previous closing price
  46. """
  47. resp = self.client.quote(symbol)
  48. return {
  49. 'current_price': resp['c'],
  50. 'change': resp['d'],
  51. 'percentage_change': resp['dp'],
  52. 'day_high': resp['h'],
  53. 'day_low': resp['l'],
  54. 'day_open_price': resp['o'],
  55. 'previous_close_price': resp['pc'],
  56. }
  57. ```
  58. If we run our code with
  59. ```python
  60. service = FinHubService()
  61. print(service.get_price_of_stock("AAPL"))
  62. ```
  63. We get something like:
  64. ```json
  65. {'current_price': 199.74, 'change': 6.58, 'percentage_change': 3.4065, 'day_high': 201.59, 'day_low': 195.97, 'day_open_price': 196.12, 'previous_close_price': 193.16}
  66. ```
  67. ## The Crawler Service
  68. Now that we have our Retriever, we want a very simple crawler to search on Google for information and read the web pages returned as results.
  69. ```python
  70. class SerperDevService:
  71. def __init__(self):
  72. self.__api_key__=os.getenv("SERPER_DEV_API_KEY")
  73. self.search_url = "https://google.serper.dev/search"
  74. self.scraper_url = "https://scrape.serper.dev"
  75. def search_google(
  76. self,
  77. query: str,
  78. n_results: int = 10,
  79. page: int = 1,
  80. ) -> List[Dict[str, Any]]:
  81. """
  82. Search Google using the Serper.dev API.
  83. :param query: the query to search on google
  84. :param n_results: number of results to return per page
  85. :param page: page number to return
  86. :return: a list of dictionaries containing the search results
  87. """
  88. payload = json.dumps(
  89. {
  90. "q": query,
  91. "num": n_results,
  92. "page": page
  93. },
  94. )
  95. headers = {
  96. 'X-API-KEY': self.__api_key__,
  97. 'Content-Type': 'application/json'
  98. }
  99. response = requests.request(
  100. method="POST",
  101. url=self.search_url,
  102. headers=headers,
  103. data=payload,
  104. )
  105. return response.json()['organic']
  106. def get_text_from_page(self, url_to_scrape: str) -> str:
  107. """
  108. Get text from a page using the Serper.dev API.
  109. :param url_to_scrape: the url of the page to scrape
  110. :return: the text content of the page
  111. """
  112. payload = json.dumps(
  113. {
  114. "url": url_to_scrape,
  115. }
  116. )
  117. headers = {
  118. 'X-API-KEY': self.__api_key__,
  119. 'Content-Type': 'application/json'
  120. }
  121. response = requests.request(
  122. method="POST",
  123. url=self.scraper_url,
  124. headers=headers,
  125. data=payload,
  126. )
  127. return response.text
  128. ```
  129. ## From Service to Server
  130. It is now time to transform those two services into MCP server(s). Given the limited capabilities of the agents in this tutorial, we could create a single MCP server that provides all the tools needed by the agent(s). Nonetheless, the goal here is not to have the best production-ready solution, quite the contrary, but on the other hand to experiment: for this reason, we will create two servers, one per service.
  131. Within the Model Context Protocol, servers come in two flavors distinguished by their transport layer. An STDIO MCP server runs as a local subprocess and pipes JSON-RPC messages over its own stdin/stdout streams, giving minimal latency, full-duplex messaging, and zero network dependencies: it is ideal for command-line tools or same-machine integrations. A Server-Sent Events (SSE) MCP server instead exposes an HTTP endpoint: the client sends requests with lightweight POSTs while the server pushes results back on a single SSE stream, making it naturally web-friendly and accessible across networks or from a browser. In practice, stdio is the lean, no-frills option when everything lives on one host, whereas SSE trades a bit of HTTP overhead and one-way streaming semantics for firewall traversal, browser compatibility, and remote reach.
  132. Given our use case, it seems natural to use the first solution (but we will discover it is not that simple).
  133. ```python
  134. mcp = FastMCP("Search Engine Server")
  135. search_service = SerperDevService()
  136. @mcp.tool()
  137. def search_google(
  138. query: str,
  139. n_results: int = 10,
  140. page: int = 1,
  141. ) -> list:
  142. """
  143. Search Google using the Serper.dev API.
  144. :param query: the query to search on google
  145. :param n_results: number of results to return per page
  146. :param page: page number to return
  147. :return: a list of dictionaries containing the search results
  148. """
  149. return search_service.search_google(query, n_results, page)
  150. @mcp.tool()
  151. def get_text_from_page(url_to_scrape: str) -> str:
  152. """
  153. Get text from a page using the Serper.dev API.
  154. :param url_to_scrape: the url of the page to scrape
  155. :return: the text content of the page
  156. """
  157. return search_service.get_text_from_page(url_to_scrape)
  158. if __name__ == "__main__":
  159. mcp.run(transport='stdio')
  160. ```
  161. The code is straightforward (and highly similar to FastAPI, not surprisingly, given that it is used to implement this MCP library).
  162. We first initialise the MCP server with `mcp = FastMCP("<NAME_OF_SERVER>")`, then, we define the endpoint/tools using the decorator `@mcp.tool()`.
  163. We define the Stocks scraper MCP server in the very same way.
  164. ## Let's use the MCP Server
  165. So, at this point we have our working MCP server and we just need to use it. Given this tutorial is about A2A Framework as well, and A2A has been created by Google, we will use the new google ADK to create our agents. To start, we create a single, simple agent that use our MCP server to search the web for information.
  166. We first create a function that spawns our MCP server and "transforms" it into a tool for our ADK agent.
  167. ```python
  168. async def get_tools_async():
  169. """Gets tools from the Search MCP Server."""
  170. print("Attempting to connect to MCP Filesystem server...")
  171. tools, exit_stack = await MCPToolset.from_server(
  172. connection_params=StdioServerParameters(
  173. command="/opt/homebrew/bin/uv", # on macos you need to use this path
  174. args=[
  175. "--directory",
  176. "/root/path/to/mcp_server",
  177. "run",
  178. "search_server.py"
  179. ],
  180. env={
  181. "PYTHONPATH": <YOUR_PYTHONPATH_IF_NEEDED>
  182. },
  183. )
  184. )
  185. print("MCP Toolset created successfully.")
  186. return tools, exit_stack
  187. ```
  188. This function will spawn our MCP server and return the tools and the exit stack.
  189. Now, we can create our agent in a similar fashion.
  190. ```python
  191. async def get_agent_async():
  192. """Creates an ADK Agent equipped with tools from the MCP Server."""
  193. tools, exit_stack = await get_tools_async()
  194. print(f"Fetched {len(tools)} tools from MCP server.")
  195. root_agent = LlmAgent(
  196. model='gemini-2.5-pro-exp-03-25',
  197. name='search_agent',
  198. description="Agent to answer questions using Google Search.",
  199. instruction="You are an expert researcher. When someone asks you something you always double check online. You always stick to the facts.",
  200. tools=tools, #
  201. )
  202. return root_agent, exit_stack
  203. ```
  204. This function will create an ADK agent equipped with the tools from the MCP server.
  205. We can now put everything together and create our agent pipeline.
  206. ```python
  207. async def async_main():
  208. session_service = InMemorySessionService()
  209. artifacts_service = InMemoryArtifactService()
  210. print("Creating session...")
  211. session = session_service.create_session(
  212. state={}, app_name='mcp_search_app', user_id='searcher_usr', session_id='searcher_session'
  213. )
  214. print(f"Session created with ID: {session.id}")
  215. query = "What are the most tipical sports of the Aosta Valley? Answer with a lot of details."
  216. print(f"User Query: '{query}'")
  217. content = types.Content(role='user', parts=[types.Part(text=query)])
  218. root_agent, exit_stack = await get_agent_async()
  219. runner = Runner(
  220. app_name='mcp_search_app',
  221. agent=root_agent,
  222. artifact_service=artifacts_service,
  223. session_service=session_service,
  224. )
  225. print("Running agent...")
  226. events_async = runner.run_async(
  227. session_id=session.id, user_id=session.user_id, new_message=content
  228. )
  229. async for event in events_async:
  230. if event.is_final_response():
  231. if event.content and event.content.parts:
  232. final_response_text = event.content.parts[0].text
  233. elif event.actions and event.actions.escalate: # Handle potential errors/escalations
  234. final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}"
  235. print(f"############# Final Response #############\n\n{final_response_text}")
  236. break
  237. print("Closing MCP server connection...")
  238. await exit_stack.aclose()
  239. print("Cleanup complete.")
  240. ```
  241. This function will create a session, run the agent, and print the final response (If you are interested in the answer to the question about the Aosta Valley, you can see below).
  242. <details>
  243. <summary>If you are interested in the answer to the question about the Aosta Valley, click here</summary>
  244. Okay, here are the traditional sports specific to the Aosta Valley, with detailed explanations of how they are played:
  245. The Aosta Valley boasts several unique traditional sports, deeply rooted in its rural history and culture, primarily played in spring and autumn. The main ones are **Tsan**, **Rebatta**, **Fiolet**, and **Palet**. Additionally, the game of **Morra** is also a popular traditional pastime.
  246. * **Tsan**: Often compared vaguely to baseball or Romanian Oina, Tsan (meaning "field" in the local dialect) is a team sport played on a large grass field, ideally at least 135 meters long. Two teams of 12 players compete. The game involves two main phases. In the first phase ('battià' or 'tsachà'), players from one team take turns hitting a small ball ('tsan') placed in a notch ('t aspot') on a long wooden or plastic pole ('percha' or 'pertse') which rests obliquely on a stand ('bes'). The hitter uses a wooden stick ('baquet') to strike the end of the 'percha', launching the 'tsan' into the air, and then hits the airborne 'tsan' with the 'baquet' to send it downfield. The opposing team is spread across the field trying to intercept the 'tsan' before it lands, primarily using wooden paddles ('pilon' or 'boquet'), which they can even throw to block the ball. A hit is considered 'good' ('bon') if it lands within the designated field boundaries and is not intercepted. The batting player continues until their shot is intercepted, or they hit the 'tsan' out of bounds three consecutive times or four times in total. The number of 'bone' (good hits) each player accumulates is tallied for the team. After all players on the first team have batted, the teams switch roles. In the second phase ('servià' or 'paletà'), each player must convert their accumulated 'bone' into distance. A player from the opposing team throws the 'tsan' high in the air towards the original batting area. The player whose turn it is attempts to hit this thrown 'tsan' with a different wooden paddle ('paleta' or 'piota'), aiming for maximum distance. The distance of this hit is measured in meters. Finally, the total meters achieved by all players on each team are summed up. The team that accumulates an advantage of at least 40 meters over the opponent wins the match; if the difference is less, it's a draw (though in finals or play-offs, a single meter advantage is enough to win). Due to the hardness of the wooden 'tsan', players often wear helmets for safety.
  247. * **Rebatta**: This game belongs to the family of bat-and-ball sports, like golf or baseball. It involves hitting a small ball ('rebatta', made of wood studded with nails or metal, about 30mm diameter) as far as possible. To do this, the player uses two specific wooden tools. First is the 'fioletta', a pipe-shaped lever about 20cm long. The 'rebatta' is placed on the slightly hollowed end of the 'fioletta' which rests on the ground. The player then strikes the *other* end of the 'fioletta' with a long wooden club ('masetta', 100-140cm long with a distinct head called 'maciocca') making the 'fioletta' act as a lever to pop the 'rebatta' into the air (this action is called 'levoù'). Immediately after, the player swings the 'masetta' again to strike the airborne 'rebatta' forcefully, sending it downfield. The playing field is typically an isosceles triangle marked out on grass, with the vertex at the batting spot ('place'). The length varies by category but can be up to 240 meters. Lines are marked across the field every 15 meters, and landing the 'rebatta' beyond a line scores a corresponding number of points (1 point for passing the first line, 2 for the second, etc.). Matches are often played between teams (e.g., five players each), competing over a set number of turns ('bars'), with both team and individual championships held.
  248. * **Fiolet**: Similar in objective to Rebatta (hitting an object for maximum distance), Fiolet uses slightly different equipment and technique. The object hit is the 'fiolet' itself, which is ovoid-shaped with one slightly flattened part. Instead of using a separate lever like Rebatta's 'fioletta', the 'fiolet' is balanced directly on a smooth stone ('pira') or a purpose-made stand. The player uses a bat (also often called 'masetta' or 'baton') to strike the edge of the balanced 'fiolet' skillfully. This initial impact makes the 'fiolet' jump vertically into the air. The player then takes a full swing with the bat to hit the airborne 'fiolet' and drive it as far as possible down the field, potentially over 150 meters. Like Rebatta, scoring is based on the distance achieved, often measured in zones or points corresponding to set distances. Competitions include team events (often 5 players per team) and a notable individual championship where the winner receives the "Baton d'Or" (Golden Bat) trophy for the year.
  249. * **Palet**: This sport is akin to horseshoes or the French 'jeu de palets'. Players throw heavy, round, flat metal discs called 'palets' towards a smaller target pin, known as the 'bolin' or 'billet', which is placed at a distance (often around 10-20 meters) on a designated court, usually made of clay or packed earth. The objective is to land your 'palet' as close to the 'bolin' as possible. Players typically throw a set number of 'palets' per round. Scoring occurs after all 'palets' are thrown in a round. Points are awarded to the player or team whose 'palet(s)' are closest to the 'bolin'. Usually, only the 'palets' closer than the opponent's closest 'palet' can score. It requires precision and strategy in throwing the heavy discs. It's played both individually and in teams, often in dedicated courts found throughout the valley.
  250. * **Morra** (or Moura): While simpler and often considered more of a game than a sport requiring a dedicated field, Morra is a very traditional and lively pastime in the Aosta Valley. It's typically played between two people. Both players simultaneously extend one hand, showing a number of fingers from 1 to 5 (or a closed fist representing zero). At the same instant they extend their hand, each player loudly shouts out their guess for the *total* sum of fingers shown by both players combined (so the guess will be between 0 and 10). The player who correctly guesses the sum scores a point. The game is fast-paced, often played in rounds to a set score, and is known for the animated shouts and gestures involved.
  251. </details>
  252. ## Multiple Local MCP Servers: where STDIO is not enough
  253. Now, we have a single MCP server that can be used by our agent. However, especially if we plan to play with multiple agents, we want to have multiple MCP servers, each one with a specific purpose. For example, we want one MCP server to be able to search the web, another to retrieve stocks, and so on.
  254. If you try to spawn multiple STDIO-based MCP servers, you will notice that they will not work at the same time. To solve this problem, we can use an SSE-based MCP server with some tricks.
  255. It is quite simple: we declare the "endpoints" as before,
  256. ```python
  257. @mcp.tool()
  258. def search_google(
  259. query: str,
  260. n_results: int = 10,
  261. page: int = 1,
  262. ) -> list:
  263. """
  264. Search Google using the Serper.dev API.
  265. :param query: the query to search on google
  266. :param n_results: number of results to return per page
  267. :param page: page number to return
  268. :return: a list of dictionaries containing the search results
  269. """
  270. return search_service.search_google(query, n_results, page)
  271. @mcp.tool()
  272. def get_text_from_page(url_to_scrape: str) -> str:
  273. """
  274. Get text from a page using the Serper.dev API.
  275. :param url_to_scrape: the url of the page to scrape
  276. :return: the text content of the page
  277. """
  278. return search_service.get_text_from_page(url_to_scrape)
  279. ```
  280. Then, we wrap the server in a Startlette app:
  281. ```python
  282. def create_starlette_app(
  283. mcp_server: Server,
  284. *,
  285. debug: bool = False,
  286. ) -> Starlette:
  287. """
  288. Create a Starlette application that can server the provied mcp server with SSE.
  289. :param mcp_server: the mcp server to serve
  290. :param debug: whether to enable debug mode
  291. :return: a Starlette application
  292. """
  293. sse = SseServerTransport("/messages/")
  294. async def handle_sse(request: Request) -> None:
  295. async with sse.connect_sse(
  296. request.scope,
  297. request.receive,
  298. request._send,
  299. ) as (read_stream, write_stream):
  300. await mcp_server.run(
  301. read_stream,
  302. write_stream,
  303. mcp_server.create_initialization_options(),
  304. )
  305. return Starlette(
  306. debug=debug,
  307. routes=[
  308. Route("/sse", endpoint=handle_sse),
  309. Mount("/messages/", app=sse.handle_post_message),
  310. ],
  311. )
  312. ```
  313. We can then run each server with a different port as follows:
  314. ```python
  315. mcp_server = mcp._mcp_server # noqa: WPS437
  316. parser = argparse.ArgumentParser(description='Run MCP SSE-based server')
  317. parser.add_argument('--host', default='0.0.0.0', help='Host to bind to')
  318. parser.add_argument('--port', type=int, default=8080, help='Port to listen on')
  319. args = parser.parse_args()
  320. starlette_app = create_starlette_app(mcp_server, debug=True)
  321. uvicorn.run(starlette_app, host=args.host, port=args.port)
  322. ```
  323. To pass such a server to an ADK agent, as a tool we'll need something like:
  324. ```python
  325. async def return_sse_mcp_tools_search():
  326. print("Attempting to connect to MCP server for search and page read...")
  327. server_params = SseServerParams(
  328. url="http://localhost:<CHOSEN_PORT>/sse",
  329. )
  330. tools, exit_stack = await MCPToolset.from_server(connection_params=server_params)
  331. print("MCP Toolset created successfully.")
  332. return tools, exit_stack
  333. ```
  334. # Multiple Agents
  335. It is now time to create a more complex pipeline with multiple agents. At first, we will create a hierarchical crew of agents using the ADK library by Google, then, after seeing that our solution works, we will use Agent2Agent framework to create peer-to-peer agents able to coordinate with each other.
  336. ## Hierarchical Crew
  337. Now that we have our MCP servers set up, we can create a hierarchical crew of agents using the ADK library. In this example, we'll create a team of agents that can analyze companies and their stocks, with a main coordinator agent delegating tasks to specialized sub-agents.
  338. ### Setting Up the Crew
  339. First, we define some constants for our application:
  340. ```python
  341. MODEL = 'gemini-2.5-pro-exp-03-25'
  342. APP_NAME = 'company_analysis_app'
  343. USER_ID = 'searcher_usr'
  344. SESSION_ID = 'searcher_session'
  345. ```
  346. These constants define the model we'll use (Gemini 2.5 Pro), the application name, and session identifiers.
  347. ### Creating Specialized Agents
  348. We create two specialized agents, each with their own set of tools:
  349. 1. **Stock Analysis Agent**: This agent is responsible for analyzing stock data and providing insights about stock prices and market performance.
  350. ```python
  351. stock_analysis_agent = Agent(
  352. model=MODEL,
  353. name="stock_analysis_agent",
  354. instruction="Analyze stock data and provide insights.",
  355. description="Handles stock analysis and provides insights, in particular, can get the latest stock price.",
  356. tools=stocks_tools,
  357. )
  358. ```
  359. 2. **Search Agent**: This agent specializes in searching the web and reading online content.
  360. ```python
  361. search_agent = Agent(
  362. model=MODEL,
  363. name="search_agent",
  364. instruction="Expert googler. Can search anything on google and read pages online.",
  365. description="Handles search queries and can read pages online.",
  366. tools=search_tools,
  367. )
  368. ```
  369. ### The Root Agent
  370. The root agent acts as the coordinator, delegating tasks to the specialized agents based on the user's query:
  371. ```python
  372. root_agent = Agent(
  373. name="company_analysis_assistant",
  374. model=MODEL,
  375. description="Main assistant: Handles requests about stocks and information of companies.",
  376. instruction=(
  377. "You are the main Assistant coordinating a team. Your primary responsibilities are providing company and stocks reports and delegating other tasks.\n"
  378. "1. If the user asks about a company, provide a detailed report.\n"
  379. "2. If you need any information about the current stock price, delegate to the stock_analysis_agent.\n"
  380. "3. If you need to search for information, delegate to the search_agent.\n"
  381. "Analyze the user's query and delegate or handle it appropriately. If unsure, ask for clarification. Only use tools or delegate as described."
  382. ),
  383. sub_agents=[search_agent, stock_analysis_agent],
  384. output_key="last_assistant_response",
  385. )
  386. ```
  387. The root agent's instruction clearly defines its role and how it should delegate tasks to its sub-agents. It's designed to:
  388. - Provide detailed company reports
  389. - Delegate stock price queries to the stock analysis agent
  390. - Delegate search queries to the search agent
  391. - Ask for clarification when needed
  392. ### Running the Crew
  393. The main function sets up the session and runs the agent pipeline:
  394. ```python
  395. async def async_main():
  396. # Initialize services
  397. session_service = InMemorySessionService()
  398. artifacts_service = InMemoryArtifactService()
  399. # Create session
  400. session = session_service.create_session(
  401. state={},
  402. app_name=APP_NAME,
  403. user_id=USER_ID,
  404. session_id=SESSION_ID,
  405. )
  406. # Get user query
  407. query = input("Enter your query:\n")
  408. content = types.Content(role='user', parts=[types.Part(text=query)])
  409. # Initialize tools from MCP servers
  410. search_tools, search_exit_stack = await return_sse_mcp_tools_search()
  411. stocks_tools, stocks_exit_stack = await return_sse_mcp_tools_stocks()
  412. # Create and run the agent pipeline
  413. runner = Runner(
  414. app_name=APP_NAME,
  415. agent=root_agent,
  416. artifact_service=artifacts_service,
  417. session_service=session_service,
  418. )
  419. # Process events and get final response
  420. events_async = runner.run_async(
  421. session_id=session.id,
  422. user_id=session.user_id,
  423. new_message=content
  424. )
  425. async for event in events_async:
  426. if event.is_final_response():
  427. if event.content and event.content.parts:
  428. final_response_text = event.content.parts[0].text
  429. elif event.actions and event.actions.escalate:
  430. final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}"
  431. print(colored(text=f"############# Final Response #############\n\n{final_response_text}", color='green'))
  432. break
  433. else:
  434. print(event)
  435. # Cleanup
  436. await stocks_exit_stack.aclose()
  437. await search_exit_stack.aclose()
  438. ```
  439. This implementation creates a hierarchical crew where:
  440. 1. The root agent receives the user's query
  441. 2. It analyzes the query and decides whether to:
  442. - Handle it directly
  443. - Delegate to the stock analysis agent
  444. - Delegate to the search agent
  445. 3. The specialized agents use their respective MCP tools to gather information
  446. 4. The root agent coordinates the responses and provides a final answer to the user
  447. The crew will automatically delegate tasks to the appropriate agents and provide comprehensive responses combining information from both the stock market and web searches.
  448. ## Agent2Agent Crew
  449. Now, it's time to finally play with the Agent2Agent framework. As we previously said, A2A is a framework that allows agents to coordinate with each other in a peer-to-peer manner by using a standardised interface.
  450. The said agents can be implemented in any language or framework that supports the A2A interface. In this example, we will use the ADK library by Google to create the agents for simplicity.
  451. A further disclaimer: at the time of writing, the A2A implementations i've found online, comprised the one from google, are quite raw, for this example I have __heavily__ takend and modified the code from the [A2A tutorial](https://github.com/google/agent2agent/blob/main/python/agent2agent/examples/adk/adk_tutorial.ipynb) from the official repository.
  452. ### The Main Conceptual Components
  453. The Agent2Agent (A2A) protocol enables seamless interaction between autonomous AI agents. Here are its fundamental building blocks:
  454. **Agent Card**: A standardized metadata document (typically located at `/.well-known/agent.json`) that serves as an agent's digital identity card. It details the agent's capabilities, available skills, service endpoint, and security requirements, enabling other agents to discover and understand how to interact with it.
  455. **A2A Server**: An agent that implements the A2A protocol by exposing an HTTP endpoint. It handles incoming requests, manages task execution, and maintains communication with clients according to the protocol specifications.
  456. **A2A Client**: Any application or agent that consumes A2A services. It initiates interactions by sending requests (such as `tasks/send` or `tasks/sendSubscribe`) to an A2A Server's endpoint.
  457. **Task**: The primary unit of work in A2A. When a client initiates a task, it creates a unique conversation thread that can progress through various states: submitted, working, input-required, completed, failed, or canceled. Each task maintains its own context and history.
  458. **Message**: The basic unit of communication between clients and agents. Messages contain a role (either "user" or "agent") and are composed of one or more Parts, forming the conversation thread.
  459. **Part**: The atomic content unit within Messages or Artifacts. Parts can be of different types:
  460. - TextPart: For plain text content
  461. - FilePart: For file data (either inline or referenced via URI)
  462. - DataPart: For structured JSON data (commonly used for forms or structured responses)
  463. **Artifact**: Represents any output generated by an agent during task execution. This could include generated files, structured data, or other resources. Like Messages, Artifacts are composed of Parts.
  464. **Streaming**: For tasks that require extended processing time, servers can implement streaming capabilities through `tasks/sendSubscribe`. This allows clients to receive real-time updates via Server-Sent Events (SSE), including task status changes and new artifacts.
  465. **Push Notifications**: Servers supporting this feature can proactively notify clients about task updates through a webhook URL. Clients configure their notification endpoint using `tasks/pushNotification/set`.
  466. #### Typical Interaction Flow
  467. 1. **Discovery**: The client retrieves the Agent Card from the server's well-known URL to understand the agent's capabilities and requirements.
  468. 2. **Initiation**: The client starts a new task by sending a `tasks/send` or `tasks/sendSubscribe` request, including the initial message and a unique Task ID.
  469. 3. **Processing**:
  470. - In streaming mode: The server sends real-time updates via SSE, including status changes and new artifacts
  471. - In non-streaming mode: The server processes the task synchronously and returns the final result
  472. 4. **Interaction**: If the task requires additional input, the client can send follow-up messages using the same Task ID.
  473. 5. **Completion**: The task eventually reaches a final state (completed, failed, or canceled), concluding the interaction.
  474. ### The ADKAgent Class
  475. Now that we understand the conceptual components of A2A, let's look at how we can implement it using the ADK library. The following code shows how to create an agent that can both act as a standalone agent and coordinate with other agents in the network.
  476. The `ADKAgent` class serves as the foundation for our A2A implementation. It bridges the Google ADK framework with the A2A protocol, allowing agents to communicate and coordinate tasks. Here's a breakdown of its key components:
  477. ```python
  478. class ADKAgent:
  479. """An agent that handles stock report requests."""
  480. SUPPORTED_CONTENT_TYPES = ["text", "text/plain"]
  481. def __init__(
  482. self,
  483. model: str,
  484. name: str,
  485. description: str,
  486. instructions: str,
  487. tools: List[Any],
  488. is_host_agent: bool = False,
  489. remote_agent_addresses: List[str] = None,
  490. task_callback: TaskUpdateCallback | None = None
  491. ):
  492. # ... initialization code ...
  493. ```
  494. The class can be configured in two modes:
  495. 1. **Standalone Agent**: When `is_host_agent=False`, it acts as a regular ADK agent with its own tools and capabilities
  496. 2. **Host Agent**: When `is_host_agent=True`, it becomes a coordinator that can delegate tasks to other agents
  497. #### Key Features
  498. 1. **Remote Agent Management**:
  499. ```python
  500. def register_agent_card(self, card: AgentCard):
  501. remote_connection = RemoteAgentConnections(card)
  502. self.remote_agent_connections[card.name] = remote_connection
  503. self.cards[card.name] = card
  504. ```
  505. This method allows the agent to discover and connect to other agents in the network. Each agent's capabilities are described in its `AgentCard`, which is stored in the `.well-known/agent.json` file.
  506. 2. **Task Delegation**:
  507. ```python
  508. async def send_task(
  509. self,
  510. agent_name: str,
  511. message: str,
  512. tool_context: ToolContext
  513. ):
  514. # ... task delegation code ...
  515. ```
  516. The `send_task` method handles the core A2A protocol interaction. It:
  517. - Creates a new task with a unique ID
  518. - Sends the task to the specified remote agent
  519. - Manages the task lifecycle (submitted, working, completed, etc.)
  520. - Handles responses and artifacts from the remote agent
  521. 3. **State Management**:
  522. ```python
  523. def check_state(self, context: ReadonlyContext):
  524. state = context.state
  525. if ('session_id' in state and
  526. 'session_active' in state and
  527. state['session_active'] and
  528. 'agent' in state):
  529. return {"active_agent": f'{state["agent"]}'}
  530. return {"active_agent": "None"}
  531. ```
  532. The agent maintains state information about:
  533. - Active sessions
  534. - Current tasks
  535. - Connected agents
  536. - Conversation context
  537. 4. **Response Processing**:
  538. ```python
  539. def convert_parts(parts: list[Part], tool_context: ToolContext)
  540. def convert_part(part: Part, tool_context: ToolContext)
  541. ```
  542. These methods handle the conversion between different response formats, supporting:
  543. - Text responses
  544. - Structured data
  545. - File attachments
  546. - Artifacts
  547. #### Usage Example
  548. Here's how you can use the `ADKAgent` to create a coordinator agent that delegates tasks to specialized agents:
  549. ```python
  550. # Create a host agent
  551. host_agent = ADKAgent(
  552. model="gemini-2.5-pro",
  553. name="coordinator",
  554. description="Main coordinator agent",
  555. instructions="Coordinate tasks between agents",
  556. tools=[],
  557. is_host_agent=True,
  558. remote_agent_addresses=["http://agent1:8080", "http://agent2:8080"]
  559. )
  560. ```
  561. ### The Agent Card Class
  562. In the previous piece of code, we have seen a `AgentCard` object being used in many places.
  563. The `AgentCard` class is a crucial component of the Agent2Agent (A2A) protocol, serving as a standardized way to describe an agent's capabilities and requirements. It's essentially an agent's digital identity card that other agents can use to discover and understand how to interact with it.
  564. Let's break down the key components of the `generate_agent_card` function:
  565. 1. **Basic Agent Information**:
  566. - `agent_name`: A unique identifier for the agent
  567. - `agent_description`: A human-readable description of what the agent does
  568. - `agent_url`: The endpoint where the agent can be reached
  569. - `agent_version`: The version of the agent implementation
  570. 2. **Capabilities**:
  571. - `can_stream`: Indicates if the agent supports streaming responses via Server-Sent Events (SSE)
  572. - `can_push_notifications`: Specifies if the agent can send push notifications
  573. - `can_state_transition_history`: Determines if the agent maintains a history of state transitions
  574. 3. **Communication Settings**:
  575. - `authentication`: Defines the authentication method required to interact with the agent
  576. - `default_input_modes`: Lists the supported input formats (e.g., "text", "json")
  577. - `default_output_modes`: Lists the supported output formats
  578. 4. **Skills**:
  579. - `skills`: A list of `AgentSkill` objects that describe the specific capabilities of the agent
  580. Here's an example of how to use the `generate_agent_card` function to create a card for a stock analysis agent:
  581. ```python
  582. stock_agent_card = generate_agent_card(
  583. agent_name="stock_analyzer",
  584. agent_description="Analyzes stock market data and provides insights",
  585. agent_url="http://localhost:8080",
  586. agent_version="1.0.0",
  587. can_stream=True,
  588. can_push_notifications=True,
  589. skills=[
  590. AgentSkill(
  591. name="stock_analysis",
  592. description="Analyzes stock prices and market trends",
  593. input_schema={
  594. "type": "object",
  595. "properties": {
  596. "symbol": {"type": "string"},
  597. "timeframe": {"type": "string"}
  598. }
  599. },
  600. output_schema={
  601. "type": "object",
  602. "properties": {
  603. "price": {"type": "number"},
  604. "trend": {"type": "string"}
  605. }
  606. }
  607. )
  608. ]
  609. )
  610. ```
  611. The generated agent card is typically served at the `/.well-known/agent.json` endpoint of the agent's URL. This standardized location allows other agents to discover and understand how to interact with the agent without prior knowledge of its implementation details.
  612. When another agent wants to interact with this agent, it can:
  613. 1. Fetch the agent card from `/.well-known/agent.json`
  614. 2. Verify that the agent supports the required capabilities
  615. 3. Check if the agent has the necessary skills
  616. 4. Use the provided URL and authentication method to establish communication
  617. ### The A2A Server
  618. To make the agent "contactable", we need to implement the A2A server. The server is responsible for handling incoming requests from other agents and managing the communication protocol. Here's a breakdown of the key components:
  619. 1. **Server Initialization**:
  620. ```python
  621. class A2AServer:
  622. def __init__(
  623. self,
  624. host="0.0.0.0",
  625. port=5000,
  626. endpoint="/",
  627. agent_card: AgentCard = None,
  628. task_manager: TaskManager = None,
  629. ):
  630. self.host = host
  631. self.port = port
  632. self.endpoint = endpoint
  633. self.task_manager = task_manager
  634. self.agent_card = agent_card
  635. self.app = Starlette()
  636. self.app.add_route(self.endpoint, self._process_request, methods=["POST"])
  637. self.app.add_route(
  638. "/.well-known/agent.json", self._get_agent_card, methods=["GET"]
  639. )
  640. ```
  641. The server is initialized with:
  642. - Host and port configuration
  643. - An endpoint for handling requests
  644. - An agent card describing the agent's capabilities
  645. - A task manager for handling task execution
  646. 2. **Request Processing**:
  647. ```python
  648. async def _process_request(self, request: Request):
  649. try:
  650. body = await request.json()
  651. json_rpc_request = A2ARequest.validate_python(body)
  652. if isinstance(json_rpc_request, GetTaskRequest):
  653. result = await self.task_manager.on_get_task(json_rpc_request)
  654. elif isinstance(json_rpc_request, SendTaskRequest):
  655. result = await self.task_manager.on_send_task(json_rpc_request)
  656. # ... handle other request types ...
  657. ```
  658. The server processes different types of requests:
  659. - Task creation and management
  660. - Streaming task updates
  661. - Push notifications
  662. - Task cancellation
  663. 3. **Asynchronous Server Startup**:
  664. ```python
  665. async def astart(self):
  666. if self.agent_card is None:
  667. raise ValueError("agent_card is not defined")
  668. if self.task_manager is None:
  669. raise ValueError("request_handler is not defined")
  670. config = uvicorn.Config(self.app, host=self.host, port=self.port, loop="asyncio")
  671. server = uvicorn.Server(config)
  672. # start in the background
  673. server_task = asyncio.create_task(server.serve())
  674. # wait for startup
  675. while not server.started:
  676. await asyncio.sleep(0.1)
  677. print("Server is up – press Ctrl+C to shut it down manually")
  678. try:
  679. await server_task
  680. except KeyboardInterrupt:
  681. server.should_exit = True
  682. await server_task
  683. ```
  684. The `astart` method is a crucial modification from the original Google implementation. Here's why:
  685. 1. **Original Implementation**:
  686. ```python
  687. def start(self):
  688. if self.agent_card is None:
  689. raise ValueError("agent_card is not defined")
  690. if self.task_manager is None:
  691. raise ValueError("request_handler is not defined")
  692. uvicorn.run(self.app, host=self.host, port=self.port)
  693. ```
  694. The original implementation used a synchronous `start` method that blocked the main thread. This was problematic because:
  695. - It couldn't be integrated into an existing async event loop
  696. - It made it difficult to coordinate with other async components (like MCP tools)
  697. 2. **New Implementation**:
  698. The new `astart` method:
  699. - Creates a Uvicorn server with an async event loop
  700. - Starts the server in the background using `asyncio.create_task`
  701. - Waits for the server to be fully started
  702. - Handles graceful shutdown on keyboard interrupt
  703. - Can be integrated into an existing async application
  704. This change was necessary because:
  705. - MCP tools are inherently asynchronous
  706. - The server needs to be able to run alongside other async components
  707. - We need proper control over the server lifecycle
  708. 4. **Response Handling**:
  709. ```python
  710. def _create_response(self, result: Any) -> JSONResponse | EventSourceResponse:
  711. if isinstance(result, AsyncIterable):
  712. async def event_generator(result) -> AsyncIterable[dict[str, str]]:
  713. async for item in result:
  714. yield {"data": item.model_dump_json(exclude_none=True)}
  715. return EventSourceResponse(event_generator(result))
  716. elif isinstance(result, JSONRPCResponse):
  717. return JSONResponse(result.model_dump(exclude_none=True))
  718. ```
  719. The server supports two types of responses:
  720. - Regular JSON responses for immediate results
  721. - Server-Sent Events (SSE) for streaming updates
  722. This implementation allows the A2A server to:
  723. - Handle multiple concurrent requests
  724. - Support streaming responses
  725. - Integrate with async components
  726. - Provide proper error handling
  727. - Support graceful shutdown
  728. The server can now be used in an async context like this:
  729. ```python
  730. async def main():
  731. server = A2AServer(
  732. host="0.0.0.0",
  733. port=5000,
  734. agent_card=my_agent_card,
  735. task_manager=my_task_manager
  736. )
  737. await server.astart()
  738. ```
  739. This makes it possible to integrate the A2A server with other async components, such as MCP tools or other agents, while maintaining proper control over the server lifecycle.
  740. ### The A2A Card Resolver
  741. The A2A Card Resolver is a class that is used to resolve the agent card of an agent. It is used to find the agent card of an agent when it is not known. The code is quite simple:
  742. ```python
  743. class A2ACardResolver:
  744. def __init__(self, base_url, agent_card_path="/.well-known/agent.json"):
  745. self.base_url = base_url
  746. self.agent_card_path = agent_card_path.lstrip("/")
  747. def get_agent_card(self) -> AgentCard:
  748. with httpx.Client() as client:
  749. url = re.match(r'(https?://[^/]+)', self.base_url).group(1).rstrip("/")
  750. response = client.get(url + "/" + self.agent_card_path)
  751. response.raise_for_status()
  752. try:
  753. resp_dict = response.json()
  754. resp_dict['url'] = self.base_url
  755. return AgentCard(**resp_dict)
  756. except json.JSONDecodeError as e:
  757. raise A2AClientJSONError(str(e)) from e
  758. ```
  759. For some reason, the original example from Google was not working. since it "destroyed" the url while attaching the card path.
  760. ### Common Resources, utils and the rest
  761. On top of those main components, in this tutorial we have used a list of other resources, many of them unchanged from the original tutorial: the vast majority can be found [here](https://github.com/Tsadoq/a2a-mcp-tutorial/blob/dd94b826801258c17a541fc900bd792c4e4d3686/a2a_servers/common).
  762. ### Putting everything together
  763. So, now we have all the components we need to put everything together.
  764. We create the Host Agent:
  765. ```python
  766. async def run_agent():
  767. AGENT_NAME = "host_agent"
  768. AGENT_DESCRIPTION = "An agent orchestrates the decomposition of the user request into tasks that can be performed by the child agents."
  769. PORT = 12000
  770. HOST = "0.0.0.0"
  771. AGENT_URL = f"http://{HOST}:{PORT}"
  772. AGENT_VERSION = "1.0.0"
  773. MODEL = 'gemini-2.5-pro-preview-03-25'
  774. AGENT_SKILLS = [
  775. AgentSkill(
  776. id="COORDINATE_AGENT_TASKS",
  777. name="coordinate_tasks",
  778. description="coordinate tasks between agents.",
  779. ),
  780. ]
  781. list_urls = [
  782. "http://localhost:11000/google_search_agent",
  783. "http://localhost:10000/stock_agent",
  784. ]
  785. AGENT_CARD = generate_agent_card(
  786. agent_name=AGENT_NAME,
  787. agent_description=AGENT_DESCRIPTION,
  788. agent_url=AGENT_URL,
  789. agent_version=AGENT_VERSION,
  790. can_stream=False,
  791. can_push_notifications=False,
  792. can_state_transition_history=True,
  793. default_input_modes=["text"],
  794. default_output_modes=["text"],
  795. skills=AGENT_SKILLS,
  796. )
  797. host_agent = ADKAgent(
  798. model=MODEL,
  799. name="host_agent",
  800. description="",
  801. tools=[],
  802. instructions="",
  803. is_host_agent=True,
  804. remote_agent_addresses=list_urls,
  805. )
  806. task_manager = generate_agent_task_manager(
  807. agent=host_agent,
  808. )
  809. server = A2AServer(
  810. host=HOST,
  811. port=PORT,
  812. endpoint="/host_agent",
  813. agent_card=AGENT_CARD,
  814. task_manager=task_manager
  815. )
  816. print(f"Starting {AGENT_NAME} A2A Server on {AGENT_URL}")
  817. await server.astart()
  818. ```
  819. The Search Agent:
  820. ```python
  821. import asyncio
  822. from typing import List, Any
  823. from dotenv import load_dotenv, find_dotenv
  824. from google.adk import Agent
  825. from google.adk.tools import google_search
  826. from a2a_servers.agent_servers.utils import generate_agent_task_manager, generate_agent_card
  827. from a2a_servers.agents.adk_agent import ADKAgent
  828. from a2a_servers.common.agent_task_manager import AgentTaskManager
  829. from a2a_servers.common.server.server import A2AServer
  830. from a2a_servers.common.types import (
  831. AgentCard,
  832. AgentCapabilities,
  833. AgentSkill,
  834. )
  835. from adk_agents_testing.mcp_tools.mcp_tool_search import return_sse_mcp_tools_search
  836. load_dotenv(find_dotenv())
  837. async def run_agent():
  838. AGENT_NAME = "google_search_agent"
  839. AGENT_DESCRIPTION = "An agent that handles search queries and can read pages online."
  840. HOST = "0.0.0.0"
  841. PORT = 11000
  842. AGENT_URL = f"http://{HOST}:{PORT}"
  843. AGENT_VERSION = "1.0.0"
  844. MODEL = 'gemini-2.5-pro-preview-03-25'
  845. AGENT_SKILLS = [
  846. AgentSkill(
  847. id="GOOGLE_SEARCH",
  848. name="google_search",
  849. description="Handles search queries and can read pages online.",
  850. ),
  851. ]
  852. AGENT_CARD = generate_agent_card(
  853. agent_name=AGENT_NAME,
  854. agent_description=AGENT_DESCRIPTION,
  855. agent_url=AGENT_URL,
  856. agent_version=AGENT_VERSION,
  857. can_stream=False,
  858. can_push_notifications=False,
  859. can_state_transition_history=True,
  860. default_input_modes=["text"],
  861. default_output_modes=["text"],
  862. skills=AGENT_SKILLS,
  863. )
  864. gsearch_tools, g_search_exit_stack = await return_sse_mcp_tools_search()
  865. google_search_agent = ADKAgent(
  866. model=MODEL,
  867. name="google_search_agent",
  868. description="Handles search queries and can read pages online.",
  869. tools=gsearch_tools,
  870. instructions=(
  871. "You are an expert googler. Can search anything on google and read pages online."
  872. ),
  873. )
  874. task_manager = generate_agent_task_manager(
  875. agent=google_search_agent,
  876. )
  877. server = A2AServer(
  878. host=HOST,
  879. port=PORT,
  880. endpoint="/google_search_agent",
  881. agent_card=AGENT_CARD,
  882. task_manager=task_manager
  883. )
  884. print(f"Starting {AGENT_NAME} A2A Server on {AGENT_URL}")
  885. await server.astart()
  886. if __name__ == "__main__":
  887. asyncio.run(
  888. run_agent()
  889. )
  890. ```
  891. And the Stock Agent:
  892. ```python
  893. async def run_agent():
  894. AGENT_NAME = "stock_report_agent"
  895. AGENT_DESCRIPTION = "An agent that provides US stock prices and info."
  896. PORT = 10000
  897. HOST = "0.0.0.0"
  898. AGENT_URL = f"http://{HOST}:{PORT}"
  899. AGENT_VERSION = "1.0.0"
  900. MODEL = 'gemini-2.5-pro-preview-03-25'
  901. AGENT_SKILLS = [
  902. AgentSkill(
  903. id="SKILL_STOCK_REPORT",
  904. name="stock_report",
  905. description="Provides stock prices and info.",
  906. ),
  907. ]
  908. AGENT_CARD = generate_agent_card(
  909. agent_name=AGENT_NAME,
  910. agent_description=AGENT_DESCRIPTION,
  911. agent_url=AGENT_URL,
  912. agent_version=AGENT_VERSION,
  913. can_stream=False,
  914. can_push_notifications=False,
  915. can_state_transition_history=True,
  916. default_input_modes=["text"],
  917. default_output_modes=["text"],
  918. skills=AGENT_SKILLS,
  919. )
  920. stocks_tools, stocks_exit_stack = await return_sse_mcp_tools_stocks()
  921. stock_analysis_agent = ADKAgent(
  922. model=MODEL,
  923. name="stock_analysis_agent",
  924. description="Handles stock analysis and provides insights, in particular, can get the latest stock price.",
  925. tools=stocks_tools,
  926. instructions=(
  927. "Analyze stock data and provide insights. You can also get the latest stock price."
  928. "If the user asks about a company, the stock prices for the said company."
  929. "If the user asks about a stock, provide the latest stock price and any other relevant information."
  930. "You can get only the latest stock price for US companies."
  931. ),
  932. )
  933. task_manager = generate_agent_task_manager(
  934. agent=stock_analysis_agent,
  935. )
  936. server = A2AServer(
  937. host=HOST,
  938. port=PORT,
  939. endpoint="/stock_agent",
  940. agent_card=AGENT_CARD,
  941. task_manager=task_manager
  942. )
  943. print(f"Starting {AGENT_NAME} A2A Server on {AGENT_URL}")
  944. await server.astart()
  945. ```
  946. Then, run everything.
  947. First the MCP Servers:
  948. ```bash
  949. uv run mcp server/sse/search_server.py
  950. ```
  951. ```bash
  952. uv run mcp server/sse/stocks_server.py
  953. ```
  954. And then the A2A Servers:
  955. ```bash
  956. uv run a2a_servers/agent_servers/stock_report_agent_server.py
  957. ```
  958. ```bash
  959. uv run a2a_servers/agent_servers/google_search_agent_server.py
  960. ```
  961. And finally, the Host Agent:
  962. ```bash
  963. uv run a2a_servers/host_agent_server.py
  964. ```
  965. We can then contact the host agent (e.g, using the script at `a2a_servers/run_from_local_client.py`).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.