Connect Your Moodle LMS to AI via MCP Server

Students relying on AI for study help often face a tedious workflow: copying PDFs, pasting them into chat interfaces, and losing context between sessions. This manual process breaks the flow of learning and makes it difficult to reference specific course notes later. A more robust solution exists in the Model Context Protocol (MCP), which standardizes how AI models interact with external data sources. By using MCP, you can create a reusable bridge between your LMS and any compatible AI client, ensuring consistent access to your course materials without the friction of manual data entry.
By building a custom MCP server, you can connect your Moodle learning management system directly to an AI assistant. This setup allows you to ask questions about your course material without leaving your preferred interface. The server acts as a bridge, fetching relevant content from your LMS and providing it to the model in a structured format, eliminating the need for repetitive copy-pasting. This approach transforms static course materials into an interactive knowledge base that is always up to date.
This guide walks you through creating a Python-based MCP server that integrates with Moodle. You will learn how to handle authentication, fetch course resources, and expose them as tools or resources to an AI client. The approach is flexible, working with any OpenAI-compatible endpoint, including free alternatives like KeyAPIFreeAnthropic. Note that while KeyAPIFreeAnthropic offers a free, keyless API, it is not affiliated with Anthropic, so you are not accessing Anthropic's proprietary models or keys. The server handles the data fetching, while the model handles the reasoning, allowing you to swap models without changing the server logic.
Frequently asked questions
What is the Model Context Protocol?
The Model Context Protocol is an open standard that enables AI models to securely connect to external data sources. It defines how clients and servers exchange context, tools, and resources. By using MCP, you can create a reusable bridge between your LMS and any compatible AI client, ensuring consistent access to your course materials. It standardizes the interaction, making it easier to integrate different AI tools with your specific data sources.
How does an MCP server differ from a simple API wrapper?
An MCP server exposes standardized capabilities like tools, resources, and prompts to an AI client. A simple API wrapper just returns data. MCP allows the AI to discover available features dynamically, understand their schemas, and invoke them contextually. This makes the integration more robust and adaptable to different AI clients, allowing for more complex interactions than a basic wrapper.
Which is better: a custom MCP server or a third-party tool?
A custom MCP server offers full control over data access, security, and context handling. Third-party tools may be easier to set up but often lack flexibility or charge recurring fees. For students who want a permanent, cost-effective solution that respects their specific Moodle structure, a custom server is superior. You can also compare this with other MCP setups like the Outlook MCP server for email workflows.
Is this setup compatible with all AI models?
Yes, as long as the AI client supports the MCP standard. The server itself is protocol-agnostic regarding the model. You can connect it to any OpenAI-compatible endpoint, including free services. The server handles the data fetching, while the model handles the reasoning. This separation allows you to swap models without changing the server logic, giving you freedom to choose the best model for your needs.
How do I handle Moodle authentication in MCP?
You can store your Moodle token in environment variables or a secure config file. The MCP server reads these credentials when initializing the connection to Moodle’s REST API. This ensures that your login details are not exposed in the codebase or transmitted repeatedly. The server manages the session, ensuring secure access to your course data without exposing sensitive information.
Why does my MCP server hit rate limits?
Moodle’s REST API has its own rate limits, independent of the AI provider. If your server fetches too much data too quickly, Moodle may block requests. You should implement caching or request throttling in your server logic. This prevents overwhelming Moodle’s servers and ensures consistent performance. You can also check why your free API hits rate limits for broader context on API constraints.
Can I use this with free AI endpoints?
Absolutely. The MCP server is agnostic to the backend model. You can connect it to free, keyless APIs or premium services. The server handles the Moodle data, and the AI client handles the model interaction. This flexibility allows you to experiment with different models without rebuilding the integration. See why Sonnet returns blank responses if you encounter issues with specific models.
What is the context window limit for this setup?
The context window depends on the AI model you connect, not the MCP server. The server sends only the relevant excerpts from Moodle, keeping the payload small. This helps you stay within token limits and reduces costs. You can configure the server to fetch summaries first, then detailed content as needed. This approach maximizes the utility of your context window and ensures efficient use of resources.
Step by step
- Install Dependencies — Set up a Python virtual environment and install the mcp, requests, and python-dotenv libraries. This prepares your environment for building the server.
- Configure Credentials — Generate a Moodle token and store it in a .env file. Load this token in your server script to authenticate with Moodle’s API.
- Build Server Logic — Write Python code to fetch courses and files from Moodle. Expose this data as MCP resources and tools using the mcp library.
- Test with Inspector — Use the MCP Inspector to test your server’s resources and tools. Verify that data is fetched correctly and formatted properly.
- Connect AI Client — Configure your AI client to connect to the MCP server. Start asking questions about your course materials to see the integration in action.
Understanding the MCP Architecture
The Model Context Protocol consists of two main components: the client and the server. The client is the AI application, such as a chat interface or coding assistant, that initiates requests. The server is your custom Python application that exposes Moodle data as standard MCP resources and tools. This separation ensures that the AI model does not need to know the specifics of Moodle’s API structure, making the system modular and easy to maintain.
In this architecture, the MCP server acts as a translator. It receives requests from the AI client, queries Moodle’s REST API, and formats the data into a structure that the AI can understand. This includes course names, file links, and content summaries. The AI client then uses this information to generate relevant answers or summaries for the student, creating a seamless experience for the user.
Client-Server Communication
The client and server communicate over a standard protocol, typically JSON-RPC over stdio or HTTP. The client sends requests to discover available tools and resources. The server responds with a list of capabilities, allowing the AI to understand what data is available. This dynamic discovery is a key advantage of MCP over static integrations, allowing for flexible and adaptive AI interactions.
Resource vs. Tool
Resources are static data sources, such as a course syllabus or a list of files. Tools are dynamic actions, such as searching for a specific term in the course materials. By exposing both, you give the AI flexibility. It can read a resource for context or invoke a tool to perform a specific query on Moodle’s database, enhancing the depth of the AI's understanding.
import mcp.server
app = mcp.server.App()
@app.resource("moodle://courses")
def get_courses():
return {"courses": []}Setting Up the Python Environment
Before building the server, you need a Python environment with the necessary libraries. The primary library is mcp, which provides the core protocol implementation. You will also need requests to communicate with Moodle’s REST API, and python-dotenv to manage your credentials securely. These libraries are lightweight and easy to install using pip, ensuring a smooth setup process.
Create a virtual environment to isolate your dependencies. This ensures that your MCP server does not conflict with other Python projects. Once the environment is ready, install the required packages. You will also need to set up a configuration file to store your Moodle site URL, username, and token. This setup keeps your credentials secure and easy to update, reducing the risk of exposure.
Installing Dependencies
Use pip to install the mcp library and its dependencies. The library provides classes for handling resources, tools, and prompts. You can also install uvicorn if you plan to run the server over HTTP, though stdio is preferred for local development. These tools form the backbone of your MCP server, providing the necessary infrastructure for communication.
Configuring Credentials
Create a .env file to store your Moodle token. Use the python-dotenv library to load these variables into your script. This approach keeps your credentials out of the source code, making it safe to share your server’s code on GitHub. You can also use environment variables directly in your deployment environment, ensuring security across different stages.
pip install mcp requests python-dotenv
Connecting to Moodle REST API
Moodle provides a robust REST API that allows external applications to interact with course data. You can fetch course lists, user details, and file contents. The API requires authentication via a token, which you can generate in your Moodle account settings. This token should be kept secure and passed in the request headers, ensuring that only authorized users can access the data.
The MCP server will use the requests library to send HTTP GET requests to Moodle’s endpoints. You will define functions to fetch courses, modules, and files. These functions will return data in a structured format, such as JSON. The MCP server will then expose this data as resources, making it accessible to the AI client in a consistent and predictable manner.
Authentication Setup
Generate a token in Moodle and store it in your environment variables. Use the token in the wstoken parameter of your API requests. This ensures that your server has the necessary permissions to access course data. You can also use Moodle’s web service functions to fetch specific data types, such as files or grades, expanding the scope of your MCP server.
Fetching Course Data
Use the core_course_get_courses function to retrieve a list of courses. This endpoint returns metadata such as course names, IDs, and descriptions. You can then use this information to build a list of available resources for the AI client. This data forms the basis of your knowledge base, allowing the AI to provide context-aware answers.
import requests
MOODLE_URL = "https://your-moodle.com"
TOKEN = "your-token"
def get_courses():
url = f"{MOODLE_URL}/webservice/rest/server.php"
params = {
"wstoken": TOKEN,
"wsfunction": "core_course_get_courses",
"moodlewsrestformat": "json"
}
response = requests.get(url, params=params)
return response.json()Exposing Data as MCP Resources
Resources in MCP represent static data that the AI can read. In this setup, you can expose course lists, file contents, and module descriptions as resources. The AI client can request these resources to gain context before asking questions. This approach ensures that the AI has access to the latest data from Moodle, providing a rich and accurate knowledge base for the user.
Define a resource for each course or module. The resource URI should include the course ID or module ID, allowing the AI client to request specific data. When the AI client requests a resource, your server fetches the data from Moodle and returns it in a structured format. This data can then be used to generate summaries or answer questions, enhancing the learning experience.
Resource URIs
Use URIs like moodle://course/123 to identify specific courses. This naming convention makes it easy for the AI client to understand the structure of your data. You can also use sub-URIs for files or modules, such as moodle://course/123/file/456. This hierarchical structure mirrors Moodle’s organization, making it intuitive for both developers and users.
Resource Content
The content of a resource can be text, JSON, or binary data. For course materials, text or JSON is preferred. You can fetch the content of a file from Moodle and return it as text. This allows the AI to read and summarize the document directly. Ensure that the content is formatted clearly, with headings and paragraphs intact, to improve readability.
@app.resource("moodle://course/{course_id}")
def get_course_content(course_id):
# Fetch content from Moodle API
content = fetch_moodle_content(course_id)
return {"content": content}
Implementing Search Tools
Tools allow the AI to perform dynamic actions, such as searching for a specific term in your course materials. You can implement a tool that queries Moodle’s database for keywords. This tool can return relevant excerpts or file links, helping the AI provide precise answers. Tools are more flexible than resources, as they can return different results based on the input, allowing for more complex interactions.
Define a tool called search_moodle that takes a query string as input. The tool will use Moodle’s search API or a local index to find relevant content. It will return a list of results, including titles, snippets, and links. The AI client can then use these results to generate a comprehensive answer, providing a more thorough response to the user's question.
Tool Schema
Define the tool’s schema with parameters such as query and course_id. This schema tells the AI client what inputs are required. The AI can then generate appropriate queries based on the user’s question. This ensures that the tool is used correctly and efficiently, reducing the chance of errors and improving the overall user experience.
Tool Execution
When the AI invokes the tool, your server executes the search function. It fetches the results from Moodle and formats them into a response. The response includes the relevant excerpts and links. This data is then returned to the AI, which uses it to generate the final answer. This process is fast and accurate, providing a seamless user experience.
@app.tool("search_moodle")
def search(query: str):
results = search_moodle_api(query)
return {"results": results}Handling File Downloads
Students often need access to specific files, such as PDFs or Word documents. Your MCP server can expose these files as resources or tools. When the AI client requests a file, your server fetches it from Moodle and returns the content. This allows the AI to read and summarize the document directly, without the user needing to download it manually, saving time and effort.
Implement a tool that fetches file content by ID. The tool should return the file’s metadata, such as name and size, along with its content. For binary files, you can return the base64-encoded content or a download link. This flexibility ensures that the AI can handle various file types effectively, providing a comprehensive solution for students.
File Metadata
Include metadata such as file name, type, and size in the response. This helps the AI understand the file’s context and format. You can also include a preview or summary of the file’s content, making it easier for the AI to generate a relevant answer. This metadata is crucial for accurate summarization and helps the AI provide more precise answers.
Content Retrieval
Use Moodle’s file API to fetch the content. Ensure that the content is decoded correctly, especially for text files. For binary files, you may need to convert them to a format that the AI can process, such as text or images. This step ensures that the AI can access all relevant course materials, providing a complete learning experience.
@app.tool("get_file_content")
def get_file(file_id: str):
content = get_moodle_file(file_id)
return {"content": content}
Testing with MCP Inspector
Once your server is running, you need to test it to ensure it works correctly. The MCP Inspector is a tool that allows you to interact with your server and verify its functionality. You can use it to send requests, view responses, and debug any issues. This step is crucial before connecting the server to an AI client, ensuring that everything works as expected.
Start the MCP Inspector and connect it to your server. You can then test the resources and tools by sending requests. The Inspector will display the responses, allowing you to verify that the data is correct. This process helps you identify any bugs or performance issues early in the development cycle, saving time and effort in the long run.
Running the Inspector
Install the MCP Inspector and launch it. Connect it to your server by specifying the server’s endpoint. The Inspector will automatically discover the available resources and tools. You can then interact with them directly, testing each feature individually. This hands-on approach ensures that your server is ready for production, reducing the risk of errors.
Debugging Issues
If you encounter errors, use the Inspector’s logs to diagnose the problem. Check the request parameters and responses for any inconsistencies. You can also compare the output with Moodle’s API documentation to ensure accuracy. This debugging process helps you refine your server and improve its reliability, ensuring a smooth user experience.
mcp-inspector --server localhost:8000Connecting to an AI Client
With your MCP server running and tested, you can connect it to an AI client. The client will discover the available resources and tools, allowing it to use them in conversations. You can use any MCP-compatible client, such as a chat interface or a coding assistant. This connection enables the AI to access your Moodle data seamlessly, providing a rich and interactive learning experience.
Configure the AI client to connect to your MCP server. Specify the server’s endpoint and credentials if required. Once connected, the client will display the available tools and resources. You can then start asking questions about your course materials, and the AI will use the MCP server to fetch the relevant data, providing accurate and timely answers.
Client Configuration
Enter the MCP server’s URL in the client’s settings. Ensure that the client supports the MCP protocol. You may need to install a plugin or extension to enable MCP support. This step is straightforward and allows you to integrate your server with various AI applications, making it easy to adopt the technology.
Using Tools in Chat
When you ask a question, the AI client will invoke the appropriate tool or resource. The MCP server fetches the data from Moodle and returns it to the client. The AI then uses this data to generate an answer. This process is fast and accurate, providing a rich learning experience for students. You can also check how to fix latency messages in Dataverse MCP servers if you experience delays.
{
"mcpServers": {
"moodle": {
"url": "http://localhost:8000"
}
}
}
Test your first prompt against our free endpoint and see how it compares to the paid API in seconds.