|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import os |
| 17 | + |
| 18 | +from fastmcp import Context |
| 19 | +from fastmcp import FastMCP |
| 20 | +from fastmcp.experimental.sampling.handlers.openai import OpenAISamplingHandler |
| 21 | +from openai import OpenAI |
| 22 | + |
| 23 | +logging.basicConfig(level=logging.INFO) |
| 24 | +API_KEY = os.getenv("OPENAI_API_KEY") |
| 25 | + |
| 26 | +# Set up the server's LLM handler using the OpenAI API. |
| 27 | +# This handler will be used for all sampling requests from tools on this server. |
| 28 | +llm_handler = OpenAISamplingHandler( |
| 29 | + default_model="gpt-4o", |
| 30 | + client=OpenAI( |
| 31 | + api_key=API_KEY, |
| 32 | + ), |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +# Create the FastMCP Server instance. |
| 37 | +# The `sampling_handler` is configured to use the server's own LLM. |
| 38 | +# `sampling_handler_behavior="always"` ensures the server never delegates |
| 39 | +# sampling back to the ADK agent. |
| 40 | +mcp = FastMCP( |
| 41 | + name="SentimentAnalysis", |
| 42 | + sampling_handler=llm_handler, |
| 43 | + sampling_handler_behavior="always", |
| 44 | +) |
| 45 | + |
| 46 | + |
| 47 | +@mcp.tool |
| 48 | +async def analyze_sentiment(text: str, ctx: Context) -> dict: |
| 49 | + """Analyzes sentiment by delegating to the server's own LLM.""" |
| 50 | + logging.info("analyze_sentiment tool called with text: %s", text) |
| 51 | + prompt = f"""Analyze the sentiment of the following text as positive, |
| 52 | + negative, or neutral. Just output a single word. |
| 53 | + Text to analyze: {text}""" |
| 54 | + |
| 55 | + # This delegates the LLM call to the server's own sampling handler, |
| 56 | + # as configured in the FastMCP instance. |
| 57 | + logging.info("Attempting to call ctx.sample()") |
| 58 | + try: |
| 59 | + response = await ctx.sample(prompt) |
| 60 | + logging.info("ctx.sample() successful. Response: %s", response) |
| 61 | + except Exception as e: |
| 62 | + logging.error("ctx.sample() failed: %s", e, exc_info=True) |
| 63 | + raise |
| 64 | + |
| 65 | + sentiment = response.text.strip().lower() |
| 66 | + |
| 67 | + if "positive" in sentiment: |
| 68 | + result = "positive" |
| 69 | + elif "negative" in sentiment: |
| 70 | + result = "negative" |
| 71 | + else: |
| 72 | + result = "neutral" |
| 73 | + |
| 74 | + logging.info("Sentiment analysis result: %s", result) |
| 75 | + return {"text": text, "sentiment": result} |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + print("Starting FastMCP server with tool 'analyze_sentiment'...") |
| 80 | + # This runs the server process, which the ADK agent will connect to. |
| 81 | + mcp.run() |
0 commit comments