gnews-mcp-server

OriShmila/gnews-mcp-server

3.2

If you are the rightful owner of gnews-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

The GNews MCP Server is a Model Context Protocol server designed to fetch news articles and headlines using the GNews API, offering robust search and filtering capabilities.

Tools
2
Resources
0
Prompts
0

GNews MCP Server

A Model Context Protocol (MCP) server for fetching news articles and headlines using the GNews API.

Features

  • Search News: Search for news articles using keywords with various filtering options
  • Top Headlines: Get current trending headlines based on Google News ranking
  • Comprehensive Filtering: Filter by language, country, date range, category, and more
  • Schema Validation: Full input/output validation using JSON Schema
  • Error Handling: Robust error handling and meaningful error messages

Installation

Prerequisites

Install from Git

uvx --from git+https://github.com/yourusername/gnews-mcp-server gnews-server

Local Development

  1. Clone the repository:

    git clone https://github.com/yourusername/gnews-mcp-server.git
    cd gnews-mcp-server
    
  2. Install dependencies:

    uv sync
    
  3. Set up environment variables:

    # Create .env file
    echo "GNEWS_KEY=your_gnews_api_key_here" > .env
    
  4. Run tests:

    uv run python test_server.py
    

Configuration

Environment Variables

  • GNEWS_KEY (required): Your GNews API key from gnews.io
  • DEBUG (optional): Set to true for debug logging

Getting a GNews API Key

  1. Visit gnews.io
  2. Sign up for a free account
  3. Get your API key from the dashboard
  4. Set it as the GNEWS_KEY environment variable

Available Tools

1. search_news

Search for news articles using keywords with various filtering options.

Parameters:

  • query (required): Search keywords (supports logical operators AND, OR, NOT)
  • language: 2-letter language code (default: "en") - supported values: ar, zh, nl, en, fr, de, el, hi, it, ja, ml, mr, no, pt, ro, ru, es, sv, ta, te, uk
  • country: 2-letter country code - supported values: au, br, ca, cn, eg, fr, de, gr, hk, in, ie, it, jp, nl, no, pk, pe, ph, pt, ro, ru, sg, se, ch, tw, ua, gb, us
  • in: Search in "title", "description", "content" (default: "title,description")
  • sortby: Sort by "publishedAt" or "relevance" (default: "publishedAt")
  • start_date: Start date in YYYY-MM-DD format
  • end_date: End date in YYYY-MM-DD format

Returns exactly 10 articles.

Example:

{
  "query": "artificial intelligence",
  "language": "en",
  "country": "us",
  "sortby": "relevance",
  "start_date": "2024-01-01",
  "end_date": "2024-01-31"
}

2. get_top_headlines

Get current trending headlines based on Google News ranking.

Parameters:

  • category: Category ("general", "world", "nation", "business", "technology", "entertainment", "sports", "science", "health") - default: "general"
  • language: 2-letter language code (default: "en") - supported values: ar, zh, nl, en, fr, de, el, hi, it, ja, ml, mr, no, pt, ro, ru, es, sv, ta, te, uk
  • country: 2-letter country code - supported values: au, br, ca, cn, eg, fr, de, gr, hk, in, ie, it, jp, nl, no, pk, pe, ph, pt, ro, ru, sg, se, ch, tw, ua, gb, us
  • query: Search keywords within headlines
  • start_date: Start date in YYYY-MM-DD format
  • end_date: End date in YYYY-MM-DD format

Returns exactly 10 articles.

Example:

{
  "category": "technology",
  "language": "en",
  "country": "us"
}

MCP Client Configuration

Claude Desktop

Add to your Claude Desktop configuration file:

{
  "mcpServers": {
    "gnews": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/yourusername/gnews-mcp-server",
        "gnews-server"
      ],
      "env": {
        "GNEWS_KEY": "your_gnews_api_key_here"
      }
    }
  }
}

Other MCP Clients

The server communicates using the standard MCP protocol over stdio. Refer to your MCP client's documentation for configuration details.

Query Syntax

The GNews API supports advanced query syntax for the query parameter:

Phrase Search

  • "Apple iPhone" - Exact phrase matching

Logical Operators

  • Apple AND iPhone - Both terms must be present
  • Apple OR Microsoft - Either term must be present
  • Apple NOT iPhone - First term without second term

Complex Queries

  • (Apple AND iPhone) OR (Google AND Pixel) - Complex logical combinations
  • "machine learning" AND NOT "deep learning" - Phrase with exclusion

Supported Languages

LanguageCodeLanguageCode
ArabicarItalianit
ChinesezhJapaneseja
DutchnlNorwegianno
EnglishenPortuguesept
FrenchfrRussianru
GermandeSpanishes
GreekelSwedishsv
HindihiUkrainianuk

Supported Countries

CountryCodeCountryCode
AustraliaauJapanjp
BrazilbrNetherlandsnl
CanadacaNorwayno
ChinacnPakistanpk
EgyptegPortugalpt
FrancefrSingaporesg
GermanydeSpaines
IndiainSwedense
ItalyitUnited Kingdomgb
United Statesus(and more...)

Testing

The server includes comprehensive tests:

# Run all tests
uv run python test_server.py

# Test features:
# - Schema validation
# - Input/output validation  
# - Error handling
# - Tool functionality

Development

Project Structure

gnews-mcp-server/
ā”œā”€ā”€ gnews_mcp_server/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ __main__.py         # Entry point
│   ā”œā”€ā”€ server.py           # MCP server implementation
│   ā”œā”€ā”€ handlers.py         # Tool implementations
│   └── tools.json          # Tool schemas
ā”œā”€ā”€ test_cases.json         # Test definitions
ā”œā”€ā”€ test_server.py          # Test framework
ā”œā”€ā”€ pyproject.toml          # Project configuration
└── README.md

MCP Schema Design Rules

This project follows specific patterns for MCP JSON schema design:

Optional Parameters Pattern

āœ… DO - Use nullable union types for optional parameters:

{
  "country": {
    "type": ["string", "null"],
    "description": "2-letter country code (optional)",
    "enum": ["us", "gb", "ca", ...]
  }
}

āŒ DON'T - Use default: null with non-nullable types:

{
  "country": {
    "type": "string",
    "default": null  // Type inconsistency!
  }
}
Parameters with Explicit Defaults

āœ… DO - Keep meaningful defaults for parameters:

{
  "language": {
    "type": "string", 
    "enum": ["en", "fr", "de", ...],
    "default": "en"
  }
}
Required Array Management
  • Include in required: Only truly mandatory parameters
  • Exclude from required: All optional/nullable parameters
  • Schema validation: Catches invalid inputs before handlers
Handler Signature Matching

Match your handler function signatures to the schema:

async def search_news(query: str,                    # required
                     language: str = "en",           # has default
                     country: str = None,            # nullable optional
                     **kwargs) -> dict:

Adding New Features

  1. Update tool schemas in gnews_mcp_server/tools.json
  2. Implement tool functions in gnews_mcp_server/handlers.py
  3. Add tests to test_cases.json
  4. Run tests: uv run python test_server.py

Error Handling

The server provides comprehensive error handling:

  • Validation Errors: Invalid parameters are caught and reported
  • API Errors: GNews API errors are properly formatted
  • Network Errors: Connection issues are handled gracefully
  • Schema Validation: Input/output validation ensures data integrity

Rate Limits

GNews API rate limits depend on your subscription plan:

  • Free: 100 requests per day
  • Paid Plans: Higher limits available

The server will return appropriate error messages when rate limits are exceeded.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Schema Validation Benefits

This server provides enhanced schema validation features:

  • Input Validation: Parameters validated against JSON Schema before processing
  • Output Validation: Responses validated to ensure data integrity
  • Type Safety: Nullable types properly handled with union types ["string", "null"]
  • Error Prevention: Invalid enum values, date formats, and required fields caught early
  • Consistent Behavior: Predictable parameter handling across all tools

Changelog

v0.1.0

  • Initial release
  • Search news functionality
  • Top headlines functionality
  • Comprehensive schema validation with nullable union types
  • Enhanced error handling and input validation
  • Full test suite with 100% coverage