Custom Agents
Integrate Gosset's comprehensive drug database directly into your own AI agents and applications using the Model Context Protocol (MCP). This guide shows you how to build custom agents that can access 100,000+ drug assets programmatically.
Why Build Custom Agents?
🚀 Full programmatic control over queries and responses
⚡ Unlimited access to the complete Gosset database
🔧 Custom workflows tailored to your specific use cases
🎯 Advanced filtering and data processing capabilities
📊 Integration with your existing tools and systems
Supported Frameworks
Gosset MCP server works with any MCP-compatible framework:
- OpenAI Agents SDK (Recommended)
- Custom MCP implementations
- LangChain with MCP support
- AutoGen with MCP integration
- Any framework supporting MCP protocol
OpenAI Agents SDK Integration
The OpenAI Agents SDK provides the easiest way to integrate Gosset into your custom agents.
Installation
pip install openai-agents
Authentication
You'll need a Gosset API token to access the MCP server. Set it as an environment variable:
export GOSSET_TOKEN=your_token_here
Basic Setup
import asyncio
import os
from agents import Agent, Runner
from agents.mcp import MCPServerSse
from agents.model_settings import ModelSettings
async def main():
# Connect to Gosset MCP server
async with MCPServerSse(
name="Gosset Drug Database",
params={
"url": "https://mcp.gosset.ai/sse",
"headers": {
"Authorization": f"Bearer {os.getenv('GOSSET_TOKEN')}",
},
},
cache_tools_list=True,
) as server:
# Create an agent with access to Gosset
agent = Agent(
name="Biotech Research Assistant",
instructions="""
You are a biotech research assistant with access to Gosset's
comprehensive drug database. Help users with:
- Drug discovery and competitive intelligence
- Clinical trial analysis and market research
- Target analysis and mechanism of action research
- Company pipeline analysis
Always provide detailed, accurate information from the database.
""",
mcp_servers=[server],
model_settings=ModelSettings(tool_choice="auto"),
)
# Run a query
result = await Runner.run(
agent,
"Show me all EGFR inhibitors in Phase 3 clinical trials"
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Advanced Agent Example
Here's a more sophisticated agent that combines Gosset data with custom analysis:
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerSse
from agents.model_settings import ModelSettings
class BiotechIntelligenceAgent:
def __init__(self):
self.server_config = {
"name": "Gosset Drug Database",
"params": {
"url": "https://mcp.gosset.ai/sse",
"timeout": 30,
"headers": {
"Authorization": f"Bearer {os.getenv('GOSSET_TOKEN')}",
},
},
"cache_tools_list": True,
"max_retry_attempts": 3,
}
async def create_competitive_analysis_agent(self):
"""Create an agent specialized in competitive analysis"""
async with MCPServerSse(**self.server_config) as server:
return Agent(
name="Competitive Intelligence Analyst",
instructions="""
You are an expert competitive intelligence analyst for biotech companies.
Your capabilities include:
- Comprehensive competitive landscape analysis
- Market opportunity assessment
- Clinical trial intelligence
- Patent and IP analysis
- Company pipeline evaluation
When analyzing competitive landscapes:
1. Identify all relevant drugs in the therapeutic area
2. Categorize by development phase and mechanism
3. Analyze competitive advantages and risks
4. Provide strategic recommendations
Always cite specific data points from the Gosset database.
""",
mcp_servers=[server],
model_settings=ModelSettings(
model="gpt-4o",
temperature=0.1, # Lower temperature for factual analysis
tool_choice="auto"
),
)
async def create_target_analysis_agent(self):
"""Create an agent specialized in target analysis"""
async with MCPServerSse(**self.server_config) as server:
return Agent(
name="Target Analysis Specialist",
instructions="""
You are a target analysis specialist with deep knowledge of
drug targets and mechanisms of action.
Your expertise includes:
- Target validation and druggability assessment
- Mechanism of action analysis
- Target-based competitive intelligence
- Clinical success rates by target class
- Novel target identification
When analyzing targets:
1. Provide comprehensive target information
2. List all drugs targeting the same protein/pathway
3. Analyze success rates and clinical outcomes
4. Identify gaps and opportunities
5. Suggest strategic approaches
""",
mcp_servers=[server],
model_settings=ModelSettings(
model="gpt-4o",
temperature=0.2,
tool_choice="required" # Always use tools for target queries
),
)
async def analyze_therapeutic_area(self, therapeutic_area: str):
"""Perform comprehensive analysis of a therapeutic area"""
agent = await self.create_competitive_analysis_agent()
query = f"""
Perform a comprehensive competitive analysis of the {therapeutic_area}
therapeutic area. Include:
1. Market overview and key players
2. Drugs by development phase
3. Mechanism of action distribution
4. Key targets and their validation status
5. Recent clinical trial outcomes
6. Emerging opportunities and white spaces
7. Strategic recommendations for market entry
"""
result = await Runner.run(agent, query)
return result.final_output
async def analyze_target(self, target_name: str):
"""Perform detailed target analysis"""
agent = await self.create_target_analysis_agent()
query = f"""
Provide a comprehensive analysis of {target_name} as a drug target:
1. Target biology and function
2. All drugs targeting this protein (approved and in development)
3. Clinical success rates and outcomes
4. Competitive landscape and key players
5. Mechanism diversity and approaches
6. Patent landscape and IP considerations
7. Future opportunities and challenges
"""
result = await Runner.run(agent, query)
return result.final_output
# Usage example
async def main():
intelligence_agent = BiotechIntelligenceAgent()
# Analyze oncology landscape
oncology_analysis = await intelligence_agent.analyze_therapeutic_area("oncology")
print("=== Oncology Market Analysis ===")
print(oncology_analysis)
# Analyze specific target
egfr_analysis = await intelligence_agent.analyze_target("EGFR")
print("\n=== EGFR Target Analysis ===")
print(egfr_analysis)
if __name__ == "__main__":
asyncio.run(main())
Tool Filtering and Customization
You can customize which Gosset tools your agent has access to:
from agents.mcp import create_static_tool_filter
# Create server with filtered tools
async with MCPServerSse(
name="Gosset Drug Database",
params={
"url": "https://mcp.gosset.ai/sse",
"headers": {
"Authorization": f"Bearer {os.getenv('GOSSET_TOKEN')}",
},
},
tool_filter=create_static_tool_filter(
allowed_tool_names=[
"find_drugs",
"search",
"fetch"
]
),
) as server:
# Your agent code here
pass
Alternative MCP Implementations
Using with LangChain
# Example integration with LangChain (pseudo-code)
from langchain.agents import create_openai_functions_agent
from langchain_community.tools.mcp import MCPTool
# Create MCP tools
gosset_tools = MCPTool.from_server("https://mcp.gosset.ai/sse")
# Create agent with tools
agent = create_openai_functions_agent(
llm=your_llm,
tools=gosset_tools,
prompt=your_prompt
)
Direct MCP Protocol Implementation
For maximum control, you can implement the MCP protocol directly:
import json
import asyncio
import websockets
class GossetMCPClient:
def __init__(self, server_url="wss://mcp.gosset.ai/ws"):
self.server_url = server_url
self.websocket = None
async def connect(self):
self.websocket = await websockets.connect(self.server_url)
# Initialize MCP connection
init_message = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {}
}
}
await self.websocket.send(json.dumps(init_message))
response = await self.websocket.recv()
return json.loads(response)
async def list_tools(self):
message = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}
await self.websocket.send(json.dumps(message))
response = await self.websocket.recv()
return json.loads(response)
async def call_tool(self, tool_name, arguments):
message = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
}
await self.websocket.send(json.dumps(message))
response = await self.websocket.recv()
return json.loads(response)
# Usage
async def example_direct_mcp():
client = GossetMCPClient()
await client.connect()
tools = await client.list_tools()
print("Available tools:", tools)
result = await client.call_tool("find_drugs", {
"query": "EGFR inhibitor",
"limit": 30
})
print("Search results:", result)
Best Practices
Performance Optimization
- Cache tool lists: Set
cache_tools_list=True
to avoid repeated tool discovery - Use connection pooling: Reuse MCP connections when possible
- Implement retries: Add retry logic for network issues
- Optimize queries: Use specific filters to reduce response size
Error Handling
import asyncio
from agents.exceptions import AgentException
async def robust_query(agent, query, max_retries=3):
for attempt in range(max_retries):
try:
result = await Runner.run(agent, query)
return result.final_output
except AgentException as e:
if attempt == max_retries - 1:
raise
await asyncio.sleep(2 ** attempt) # Exponential backoff
Security Considerations
- Environment variables: Store your Gosset API token and other sensitive config in environment variables
- Input validation: Validate user inputs before passing to agents
- Rate limiting: Implement rate limiting for public-facing applications
- Token security: Never commit tokens to version control; use environment variables or secure secret management
Deployment Examples
FastAPI Web Service
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import asyncio
app = FastAPI()
class QueryRequest(BaseModel):
question: str
agent_type: str = "general"
@app.post("/query")
async def query_gosset(request: QueryRequest):
try:
intelligence_agent = BiotechIntelligenceAgent()
if request.agent_type == "competitive":
result = await intelligence_agent.analyze_therapeutic_area(request.question)
elif request.agent_type == "target":
result = await intelligence_agent.analyze_target(request.question)
else:
# General query
agent = await intelligence_agent.create_competitive_analysis_agent()
result = await Runner.run(agent, request.question)
result = result.final_output
return {"result": result}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Streamlit Dashboard
import streamlit as st
import asyncio
st.title("Gosset Intelligence Dashboard")
query_type = st.selectbox(
"Select Analysis Type",
["Competitive Analysis", "Target Analysis", "General Query"]
)
user_input = st.text_area("Enter your question:")
if st.button("Analyze"):
if user_input:
with st.spinner("Analyzing..."):
intelligence_agent = BiotechIntelligenceAgent()
if query_type == "Competitive Analysis":
result = asyncio.run(
intelligence_agent.analyze_therapeutic_area(user_input)
)
elif query_type == "Target Analysis":
result = asyncio.run(
intelligence_agent.analyze_target(user_input)
)
else:
# General query implementation
pass
st.write(result)
Troubleshooting
Common Issues
- Connection timeouts: Increase timeout values in server configuration
- Tool not found errors: Verify tool names using
list_tools()
- Authentication errors: Check server URL and authentication headers
- Rate limiting: Implement proper request throttling
Debug Mode
Enable debug logging to troubleshoot issues:
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("agents.mcp")
Further Reading
Support
For technical support with custom agent development:
- Review the OpenAI Agents SDK documentation
- Check the MCP integration guide
- Contact our technical support team
- Join our developer community discussions