API Connect

API Connect

Join this online group to communicate across IBM product users and experts by sharing advice and best practices with peers and staying up to date regarding product enhancements.


#API Connect
#Applicationintegration
#APIConnect
 View Only

MCP and IBM API Connect for GraphQL

By Timil Titus posted 3 days ago

  

In today's API-driven world, GraphQL has emerged as a powerful alternative to REST, offering more flexibility and efficiency in data retrieval. IBM API Connect (APIC) for GraphQL provides a robust platform for creating, managing, and securing GraphQL APIs. This blog post will guide you through the process of creating GraphQL APIs using APIC for GraphQL and your deployed endpoint can act as an MCP server.

What is GraphQL?

GraphQL is a query language for APIs and a runtime for executing those queries against your data. Unlike REST APIs, which expose a fixed set of endpoints with predetermined data structures, GraphQL allows clients to request exactly the data they need, nothing more and nothing less. This reduces over-fetching and under-fetching of data, leading to more efficient network usage and improved application performance.

Key benefits of GraphQL include:

  • Precise data retrieval: Clients specify exactly what data they need
  • Single request: Multiple resources can be fetched in a single request
  • Strong typing: The schema defines what queries are possible
  • Introspection: APIs are self-documenting
  • Version-free: Fields can be added without breaking existing queries

Understanding APIs in the Context of AI and Automation

Before diving into APIC for GraphQL, it's important to understand how APIs fit into the modern landscape of AI and automation.

APIs: The Interface Between Applications

APIs (Application Programming Interfaces) are interfaces that applications provide to other applications. While user interfaces (UIs) like websites and mobile apps are designed for human interaction, APIs are specifically designed for application-to-application communication. The APIs provide structured data in formats like JSON, making it easy to process and integrate.

APIs and AI Agents

In the emerging world of AI, APIs play a crucial role in enabling AI agents to take actions. An AI agent is more than just a large language model (LLM) like GPT-4 or Claude. While LLMs can generate text responses, they cannot natively interact with external systems or take actions.

AI agents extend LLMs by:

  • Interacting with third-party platforms through APIs
  • Maintaining memory of previous interactions
  • Making decisions based on gathered information
  • Taking actions on behalf of users

Model Context Protocols (MCPs)

One challenge in building AI agents is the diversity of API formats and structures. Each service provider might have different API endpoints, request formats, and response structures.

Model Context Protocols (MCPs) address this challenge by providing a standardized way for AI agents to discover and interact with APIs. MCPs serve as guides that provide context about available APIs, their capabilities, and how to use them.

MCPs work in a client-server model:

  • MCP servers expose capabilities of third-party platforms and applications
  • MCP clients (within AI agents) interact with these servers

This standardization allows AI agents to dynamically discover and use APIs without requiring custom code for each integration.

Getting Started with APIC for GraphQL

IBM API Connect for GraphQL as a Service is a modern API platform that lets you build GraphQL APIs and MCP Servers for all your data sources using a declarative approach. APIs run in an in-memory Golang based GraphQL engine deployed into Kubernetes, and are highly responsive to application needs. Delivered as a fully managed SaaS, it enables developers to create concise, performant GraphQL APIs and agent ready MCP servers in minutes, deploy in seconds, and run securely without managing infrastructure.

APIs are built using a declarative approach, allowing developers to compose GraphQL schemas, federated graphs (supergraphs), and MCP endpoints by combining building blocks that describe your enterprise data. Strong introspection and schema composition mean you can model and expose your data; for applications, agents, or AI; with just a few lines of code.

The platform runs on a high-performance, in memory Golang based engine deployed to Kubernetes, delivering low latency, high throughput, and minimal backend load. At runtime, it optimizes queries and orchestrates access to your backends, whether they are public or private, SQL, NoSQL, REST, SOAP/XML, or even other GraphQL APIs.

Now that we understand the broader context, let's explore how to create GraphQL APIs using IBM API Connect and how the deployed endpoints can be used as MCP servers.

Prerequisites

  • IBM API Connect installation
  • Basic understanding of GraphQL concepts
  • Access to data sources you want to expose via GraphQL

Step 1: Define Your GraphQL Schema

The schema is the foundation of any GraphQL API. It defines the types, queries, mutations, and subscriptions available in your API.

Here's an example of a weather API schema. ie, weather.graphql

"""
The type that represents a weather grid point in the National Weather Service API
"""
type Point {
    """
    The ID of the NWS office grid
    """
    gridId: String!
    
    """
    X-coordinate in the NWS grid system
    """
    gridX: Int!
    
    """
    Y-coordinate in the NWS grid system
    """
    gridY: Int!
    
    """
    Information about the nearest city/location
    relationship Links Point to location information
    """
    relativeLocation: RelativeLocation
}

"""
The type that contains location properties for a weather point
"""
type RelativeLocation {
    """
    Location properties including city and state
    """
    properties: Properties1
}

"""
The type that represents the Location properties for a weather point
"""
type Properties1 {
    """
    
    City name
    """
    city: String
    
    """
    
    State name
    """
    state: String
}

"""
The type that describes the Weather forecast for a specific time period
"""
type Forecast {
    """
    Sequence number of the forecast period
    """
    number: Int!
    
    """
    Name of the forecast period (e.g., "Tonight", "Monday")
    """
    name: String!
    
    """
    Start time of the forecast period
    """
    startTime: DateTime!
    
    """
    End time of the forecast period
    """
    endTime: DateTime!
    
    """
    Forecasted temperature
    """
    temperature: Float!
    
    """
    
     Unit of temperature measurement (F or C)
    """
    temperatureUnit: String!
    
    """
    Temperature trend information (rising, falling, or null)
    """
    temperatureTrend: JSON
    
    """
    Brief forecast 
    """
    shortForecast: String!
    
    """
    Detailed forecast 
    """
    detailedForecast: String!
    
    """
    URL to an icon representing the forecast conditions
    """
    icon: String!
}

type Query {
    """
    The query that gets a weather grid point from latitude and longitude using the source National 
    Weather Service API and returns Point object with grid information.
    lat paramter is the Latitude coordinate.
    lng parameter is the Longitude coordinate.
    """
    getPoint(lat: Float!, lng: Float!): Point
        @rest(
            endpoint: "https://api.weather.gov/points/$lat;,$lng",
            resultroot: "properties"
        )

    """
    The query that gets forecast data for a specific NWS grid point and returns Array of Forecast objects
    office parameter is the NWS office identifier.
    gridX parameter is the X-coordinate in the grid.
    gridY parameter is the Y-coordinate in the grid.
    
    """
    getPointForecast(office: String!, gridX: Int!, gridY:Int!): [Forecast!]!
        @rest(
            endpoint: "https://api.weather.gov/gridpoints/$office/$gridX;,$gridY/forecast",
            resultroot: "properties.periods[]"
        )
    
    """
    The query gets weather forecasts for a location using lat/lng coordinates and returns Array of Forecast objects.
    lat parameter is the Latitude coordinate.
    lng parameter is the Longitude coordinate.
    In this query, First gets grid point, then uses that to get forecast
    """
    getForecast(lat: Float!, lng: Float!): [Forecast!]!
        @sequence(
            steps: [
                {
                    query: "getPoint"
                },
                {
                     query: "getPointForecast", arguments:[
                        {
                            name: "office"
                            field: "gridId"
                        }
                     ]
                }
            ]
        )
}

Now, create the index.graphql file:

"""
Schema of the Weather API that gives weather forecast data
"""
schema @sdl(files: ["weather.graphql"]) {
  query: Query
}

Create stepzen.config.json file

{
  "endpoint": "api/weather-mcp"
}

Step 2: Deploy the schema into IBM API Connect For GraphQL

  1. Log in to your environment in IBM API Connect For GraphQL using stepzen CLI.
  2. Deploy the schema using stepzen deploy

The deployed endpoint has a GraphQL endpoint at /graphql and a MCP server endpoint at /mcp. The MCP server endpoint exposes tools declared in the schema.

If no tools are declared, a GraphQL tool is automatically present that is the schema of the endpoint excluding mutations and subscriptions. That is it is the schema subset rooted at all fields in type Query.

Step 3: Connect to an LLM

Now your LLM can use your deployed endpoint as an MCP server and help to answer questions. For example, a user can ask

What is the weather forecast for tomorrow in New York ?

This will fetch the weather forecast via your MCP sever and show the details.

MCP Integration Considerations

If you plan to expose your GraphQL API through an MCP server:

  • Design your schema with AI agent interactions in mind
  • Provide clear descriptions for all types and fields
  • Consider how complex queries might be broken down into simpler operations
  • Test your API with actual AI agent interactions

Conclusion

IBM API Connect for GraphQL provides a comprehensive platform for creating, managing, and securing GraphQL APIs. By following the steps and best practices outlined in this blog post, you can build powerful, flexible, and efficient APIs that meet the needs of modern applications.

As AI agents become more prevalent, GraphQL's structured approach to data retrieval makes it an excellent choice for APIs that will be consumed by both human developers and AI systems. The integration possibilities with Model Context Protocols and Agent-to-Agent communication open up exciting new possibilities for automation and intelligence.

1 comment
11 views

Permalink

Comments

2 days ago

I enjoyed this, it was informative and simple to understand. Provided impactful insight into the main aspects of the tech.