GDELT数据查询服务

提供通过Google BigQuery访问GDELT 2.0全球事件数据库的服务,支持查询全球事件、新闻报道、主题和视觉内容,具有成本优化的工作流程。

  • by ledgerW
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 ledgerW/gdelt-mcp

使用说明

GDELT 2.0 MCP服务器

模型上下文协议服务器为AI代理提供通过Google BigQuery访问GDELT 2.0(全球事件、语言和音调数据库)的权限。使用成本优化的工作流程查询全球事件、新闻报道、主题和视觉内容。

为什么这MCP岩石🚀

  • 🎯 成本优化的工作流程:内置物化工具使迭代分析成本降低50-100倍
  • 📊 4大数据集:事件、提及、主题和视觉分析-都是可查询的
  • 🔐 安全架构:您的凭据、您的查询、您的控制
  • ⚡ 生产准备就绪:内置分区修剪、日期过滤器和成本估算
  • 🎓 CAMEO分类:用于精确查询的内置事件/参与者代码查找

快速开始

先决条件

  • Python 3.11+
  • uv 包管理器(安装)
  • 启用BigQuery API的GCP项目
  • 具有BigQuery权限的服务帐户

安装

cd gdelt-mcp
uv sync

获取GCP证书

  1. 创建GCP项目 并启用BigQuery API
  2. 创建服务帐户 在IAM和管理中
  3. 授予角色:BigQuery数据查看器+BigQuery作业用户
  4. 生成密钥:下载JSON密钥文件
  5. 提取值: project_id, private_key, client_email

运行服务器

# Development
uv run python server.py

# With FastMCP CLI
uv run fastmcp run server.py

# Interactive testing
uv run fastmcp dev server.py

认证

承载令牌格式(管道分隔):

project_id|private_key|client_email

Python示例:

from fastmcp import Client
from fastmcp.client.auth import BearerAuth

token = f"{project_id}|{private_key}|{client_email}"
client = Client("https://your-server/mcp", auth=BearerAuth(token=token))

带远程服务器的LangChain代理

创建一个LangChain代理,该代理在其系统提示中使用使用指南,并按标签组织工具:

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
import httpx

async def create_gdelt_agent():
    """Create a LangChain agent with GDELT tools organized by category."""
    
    # Bearer token format: project_id|private_key|client_email
    token = f"{project_id}|{private_key}|{client_email}"
    
    # Initialize MultiServerMCPClient with remote server
    client = MultiServerMCPClient({
        "gdelt": {
            "transport": "streamable_http",
            "url": "https://your-server/mcp",
            "auth": httpx.BasicAuth(username="", password=token),
        }
    })
    
    # Get usage guide resource
    usage_guide_blobs = await client.get_resources(
        "gdelt",
        uris="gdelt://guide/usage"
    )
    usage_guide = usage_guide_blobs[0].as_string()
    
    # Get LangChain tools (these include metadata with tags)
    tools = await client.get_tools(server_name="gdelt")
    
    # Group tools by FastMCP tags
    def group_tools_by_tag(tools):
        categories = {
            'schema': [],
            'query': [],
            'cost': [],
            'cameo': [],
            'guide': []
        }
        for tool in tools:
            # Extract tags from LangChain tool metadata
            if hasattr(tool, 'metadata') and tool.metadata:
                tags = tool.metadata.get('tags', [])
                for tag in tags:
                    if tag in categories:
                        categories[tag].append(tool.name)
        return categories
    
    tool_categories = group_tools_by_tag(tools)
    
    # Format categorized tool list for system prompt
    tools_by_category = "\n\n".join([
        f"**{category.upper()} TOOLS**:\n" + 
        "\n".join([f"- {tool}" for tool in tools])
        for category, tools in tool_categories.items()
        if tools
    ])
    
    # Build comprehensive system prompt
    system_prompt = f"""You are a GDELT data analysis assistant with access to the complete GDELT 2.0 dataset via BigQuery.

IMPORTANT USAGE GUIDE:
{usage_guide}

AVAILABLE TOOLS BY CATEGORY:
{tools_by_category}

Follow the recommended workflow from the usage guide above. Always:
1. Check existing materialized subsets first (list_materialized_subsets)
2. Create materialized subsets for iterative analysis (create_materialized_subset)
3. Use appropriate date filters in all queries
4. Start with Events table (smallest) before querying larger tables"""
    
    # Create agent with gpt-5.1
    agent = create_agent(
        "openai:gpt-5.1",
        tools,
        system_prompt=system_prompt
    )
    
    return agent

# Use the agent
agent = await create_gdelt_agent()
result = await agent.ainvoke({
    "messages": "Analyze protests in the United States during the first week of January 2025"
})
print(result)

主要特点:

  • 具有身份验证的远程服务器:使用承载令牌身份验证(project_id | private_key | client_email)
  • 使用指南集成:在系统提示中获取并包含使用指南
  • 基于标签的工具分组:按类别组织工具(模式、查询、成本、客串、指南)
  • 全面的系统提示:整合最佳实践和工具类别
  • GPT-5.1型号:实现最佳性能的最新OpenAI模型

带远程服务器的MCP客户端

使用MCP的客户端API连接到服务器,以直接访问工具和资源:

from mcp import Client
import httpx

# Bearer token format: project_id|private_key|client_email
token = f"{project_id}|{private_key}|{client_email}"
server_url = "https://gdelt-mcp.fastmcp.app/mcp"
auth = httpx.BasicAuth(username="", password=token)

client = Client(server_url, auth=auth)

async with client:
    # Get usage guide resource
    usage_guide = await client.read_resource("gdelt://guide/usage")
    print(f"Usage guide: {usage_guide[:200]}...")
    
    # List all tools
    tools = await client.list_tools()
    print(f"Available tools: {[t.name for t in tools]}")
    
    # Filter tools by tag
    schema_tools = [
        tool for tool in tools 
        if hasattr(tool, 'meta') and tool.meta and
           tool.meta.get('_fastmcp', {}) and
           'schema' in tool.meta.get('_fastmcp', {}).get('tags', [])
    ]
    
    query_tools = [
        tool for tool in tools 
        if hasattr(tool, 'meta') and tool.meta and
           tool.meta.get('_fastmcp', {}) and
           'query' in tool.meta.get('_fastmcp', {}).get('tags', [])
    ]
    
    cost_tools = [
        tool for tool in tools 
        if hasattr(tool, 'meta') and tool.meta and
           tool.meta.get('_fastmcp', {}) and
           'cost' in tool.meta.get('_fastmcp', {}).get('tags', [])
    ]
    
    print(f"Found {len(schema_tools)} schema tools")
    print(f"Found {len(query_tools)} query tools")
    print(f"Found {len(cost_tools)} cost optimization tools")

主要特点:

  • 具有身份验证的远程服务器:使用承载令牌身份验证
  • 直接资源访问:阅读使用指南和模式
  • 工具列表和过滤:按FastMCP标签筛选工具
  • 简单API:用于工具发现的简单客户端界面

可用工具标签:

  • schema:架构文档工具
  • query:直接查询工具(事件、事件提及、gkg、cloudvision)
  • cost:成本优化工具(估算、物化、列表、查询子集)
  • cameo:CAMEO分类查找工具
  • guide:使用指南和最佳做法

MCP资源

模式文档和最佳实践:

  • gdelt://events/schema -事件表(谁/什么/在哪里/何时)
  • gdelt://eventmentions/schema -媒体提及和来源
  • gdelt://gkg/schema -全球知识图谱(主题、实体)
  • gdelt://cloudvision/schema -新闻图像的视觉分析
  • gdelt://guide/usage - 经济高效的查询指南 🚨

MCP工具

查询工具

query_events -查询Events表(最小,先查询)

  • 参数: where_clause, select_fields, limit, order_by
  • ⚠️ 必需:包括 SQLDATE >= YYYYMMDD 过滤器

query_eventmentions -查询媒体对事件的提及

  • 参数: where_clause, select_fields, limit
  • 💡 推荐:使用 GLOBALEVENTID 来自事件查询

query_gkg -查询全局知识图(最大/最昂贵)

  • 参数: where_clause, select_fields, limit
  • ⚠️ 必需:包括 DATE >= YYYYMMDDhhmmss 过滤器

query_cloudvision -新闻图像查询可视化分析

  • 参数: where_clause, select_fields, limit
  • 💡 推荐:包括 timestamp 过滤器

成本优化工具

estimate_query_cost -执行前检查查询成本(模拟运行)

  • 防止昂贵的事故
  • 获取超过1GB扫描的成本警告

create_materialized_subset -创建具有自动过期功能的过滤子集

  • 过滤一次,查询多次(便宜50-100x)
  • 48小时后自动过期(可配置)
  • 必须包括日期过滤器where_clause

list_materialized_subsets -查看您的物化子集

  • 显示过期状态、大小、行数

query_materialized_subset -查询子集(近乎免费!)

  • 每个查询约0.00001美元,而全表为0.01+美元
  • 非常适合迭代分析

CAMEO分类工具

get_cameo_event_codes -获取CAMEO事件代码分类

  • 参数: category (例如“19”), search_keyword (例如,“抗议”)
  • 300+分层事件代码

get_cameo_actor_codes -获取CAMEO actor代码分类

  • 参数: code_type (“国家”、“类型”或“全部”)
  • 国家代码和参与者类型分类

成本优化的工作流程

🎯 所有分析的推荐方法:

# Step 1: Create subset once (filters data, small cost)
create_materialized_subset(
    source_table="events",
    subset_name="ukraine_jan2025",
    where_clause="SQLDATE BETWEEN 20250101 AND 20250131 AND (Actor1CountryCode = 'UKR' OR Actor2CountryCode = 'UKR')",
    select_fields="SQLDATE, Actor1Name, Actor2Name, EventCode",
    description="Ukraine events January 2025"
)

# Step 2: Query subset multiple times (near-free)
query_materialized_subset(
    subset_name="ukraine_jan2025",
    where_clause="EventCode LIKE '19%'",  # Military events
    limit=1000
)

query_materialized_subset(
    subset_name="ukraine_jan2025",
    where_clause="GoldsteinScale < -5",  # High conflict
    limit=500
)

成本比较:

  • 直接查询(3x):3×0.01美元= $0.03
  • 物化工作流程:0.01美元+3×0.00001美元= $0.01
  • 节省:66% (随着更多的查询而扩展!)

📖 阅读 gdelt://guide/usage 完整的指导资源。

查询示例

查找最近的军事冲突

query_events(
    where_clause="EventRootCode = '19' AND SQLDATE >= 20250101",
    select_fields="SQLDATE, Actor1Name, Actor2Name, EventCode",
    limit=100
)

追踪一个国家的抗议活动

query_events(
    where_clause="EventRootCode = '14' AND Actor1CountryCode = 'USA' AND SQLDATE >= 20250101",
    limit=50
)

分析媒体报道

# First get events
events = query_events(
    where_clause="Actor1Name LIKE '%Biden%' AND SQLDATE >= 20250101",
    limit=10
)

# Then get mentions for specific event
mentions = query_eventmentions(
    where_clause=f"GLOBALEVENTID = {events[0]['GLOBALEVENTID']}"
)

查找有关气候变化的文章

query_gkg(
    where_clause="Themes LIKE '%ENV_CLIMATECHANGE%' AND DATE >= 20250101000000",
    select_fields="DATE, Themes, V2Locations, V2Tone",
    limit=100
)

GDELT表概述

表 大小 更新频率 最适合
事件 小型(约100-200MB/天) 15分钟 事件跟踪、参与者分析
活动 中等(~1-2GB/天) 15分钟 来源分析、媒体报道
GKG 大型(~5-10GB/天) 15分钟 主题、实体、情感
CloudVision 变量 15分钟 视觉内容分析

查询优先级: 事件→ 提及→ GKG → CloudVision

最佳实践

  1. 始终使用日期过滤器 启用分区修剪
  2. 从事件表开始 -它是最小的
  3. 使用 estimate_query_cost 在昂贵的查询之前
  4. 创建物化子集 用于迭代分析
  5. 选择特定字段 而不是 * 在可能的情况下
  6. 检查CAMEO代码 在查询事件之前

故障排除

BigQuery访问被拒绝

  • 验证服务帐户是否具有BigQuery Data Viewer+作业用户角色
  • 检查您的GCP项目中是否启用了BigQuery API

昂贵的查询

  • 添加日期过滤器(SQLDATE或date)
  • 选择较少的字段(不 *)
  • 对重复查询使用物化
  • 检查成本 estimate_query_cost 第一

查询超时

  • 缩小日期范围
  • 限制结果数量
  • 选择更少的字段

资源

许可证

此MCP服务器实现按原样提供。GDELT数据可免费用于研究和分析。