Gujarat AGMARKNET MCP Server
README.md
# Gujarat AGMARKNET MCP Server
### AI-Powered Agricultural Market Price Intelligence using MCP, MongoDB, RAG and Playwright
The **Gujarat AGMARKNET MCP Server** is an AI-enabled agricultural market intelligence system that collects, stores, searches, and analyzes agricultural market price and arrival data from **AGMARKNET** for Gujarat.
The project uses the **Model Context Protocol (MCP)** to make agricultural market data available to AI applications such as Claude through structured tools. It also provides a **REST API**, **MongoDB-based permanent storage**, **RAG-based semantic search**, **vector embeddings**, and **automatic daily data synchronization**.
---
## ๐ Key Features
* ๐พ Gujarat agricultural market price and arrival data
* ๐ค AI integration using Model Context Protocol (MCP)
* ๐ Natural-language market data queries
* ๐๏ธ Permanent MongoDB data storage
* ๐ Commodity price and market analysis
* ๐ Historical price trend analysis
* ๐ง RAG-based semantic search
* ๐ข Vector embeddings and similarity search
* ๐ Automatic daily data synchronization
* ๐ก๏ธ Duplicate record prevention
* ๐ REST API support
* ๐งช Unit and integration testing
* ๐ฅ๏ธ MCP Inspector support
* ๐ Claude/MCP client integration
---
# ๐ Problem Statement
Agricultural market price information is available through government portals such as AGMARKNET, but accessing and analyzing this information manually can be difficult.
Users may want to ask questions such as:
* What is the wheat price in Anand?
* What was the modal price of wheat yesterday?
* Compare wheat prices between Anand and Ahmedabad.
* What is the average wheat price during a particular period?
* Show the historical price trend.
* Which market has a higher wheat price?
Traditional web interfaces require users to manually select filters and search through tables.
This project solves this problem by providing a backend system that collects agricultural market data and exposes it through **MCP tools and REST APIs**, allowing AI applications to answer such questions using structured data.
---
# ๐ฏ Objectives
The main objectives of this project are:
1. Collect agricultural market data from AGMARKNET.
2. Store historical market data permanently.
3. Automatically synchronize new market data.
4. Prevent duplicate records.
5. Provide structured APIs for market data.
6. Provide MCP tools for AI applications.
7. Implement RAG-based semantic search.
8. Analyze commodity prices and market trends.
9. Allow natural-language interaction through MCP-compatible AI clients.
10. Provide a scalable architecture for future agricultural intelligence applications.
---
# ๐๏ธ System Architecture
```text
โโโโโโโโโโโโโโโโโโโโโโโโ
โ AI Client โ
โ Claude / MCP Client โ
โโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โ MCP Protocol
โผ
โโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP Server โ
โ TypeScript / Node โ
โโโโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
MCP Tools Resources Prompts
โ
โผ
โโโโโโโโโโโโโโโโโโโ
โ Service Layer โ
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโดโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ MongoDB โ โ RAG Layer โ
โ โ โ โ
โ Market Data โ โ Embeddings โ
โ Markets โ โ Vector Search โ
โ Logs โ โ RAG Documents โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โฒ
โ
โ
โโโโโโโโดโโโโโโโโโโ
โ Ingestion โ
โ Service โ
โโโโโโโโฌโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโ
โ Playwright โ
โ Web Automation โ
โโโโโโโโโฌโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโ
โ AGMARKNET โ
โ Government Data Site โ
โโโโโโโโโโโโโโโโโโโโโโโโ
```
---
# ๐ ๏ธ Technologies Used
| Technology | Purpose |
| -------------------------------- | ---------------------------------- |
| **TypeScript** | Main programming language |
| **Node.js** | Backend runtime |
| **Express.js** | REST API server |
| **MongoDB** | Permanent data storage |
| **Mongoose / MongoDB Driver** | Database interaction |
| **Playwright** | Web automation and data collection |
| **Model Context Protocol (MCP)** | AI-client integration |
| **RAG** | Semantic information retrieval |
| **Embeddings** | Convert text into vectors |
| **Vector Search** | Semantic similarity search |
| **Zod** | Input validation |
| **node-cron** | Scheduled daily synchronization |
| **Vitest** | Testing |
| **CSV** | Historical/sample data import |
---
# ๐ Protocols and Communication
## 1. Model Context Protocol (MCP)
The project uses **Model Context Protocol** to connect AI applications with the agricultural market data system.
MCP allows an AI client to discover and use predefined tools provided by the server.
Example:
```text
User
โ
โ "What is the wheat price in Anand?"
โผ
AI Client
โ
โ MCP
โผ
AGMARKNET MCP Server
โ
โ get_commodity_price()
โผ
MongoDB
โ
โผ
Price Data
โ
โผ
AI-generated Answer
```
---
## 2. HTTP / REST
The project also provides REST APIs using HTTP.
Example:
```http
GET /api/market-data/district/Anand
```
REST APIs are useful for applications that do not directly use MCP.
---
## 3. stdio Transport
The MCP server communicates with MCP clients using **stdio transport**.
This allows MCP-compatible applications such as MCP Inspector and Claude Desktop to launch the server as a local process.
---
# ๐ Project Structure
```text
gujarat-agmarknet-mcp/
โ
โโโ src/
โ โโโ index.ts
โ โ
โ โโโ server/
โ โ โโโ mcpServer.ts
โ โ โโโ restServer.ts
โ โ
โ โโโ tools/
โ โ โโโ MCP tools
โ โ
โ โโโ resources/
โ โ โโโ MCP resources
โ โ
โ โโโ prompts/
โ โ โโโ MCP prompts
โ โ
โ โโโ services/
โ โ โโโ mongodb.ts
โ โ โโโ ingestionService.ts
โ โ โโโ marketDataService.ts
โ โ โโโ embeddingService.ts
โ โ โโโ ragService.ts
โ โ โโโ vectorSearchService.ts
โ โ โ
โ โ โโโ agmarknet/
โ โ โโโ agmarknetService.ts
โ โ โโโ marketDataSource.ts
โ โ โโโ selectors.ts
โ โ
โ โโโ models/
โ โโโ repositories/
โ โโโ routes/
โ โโโ controllers/
โ โโโ middleware/
โ โโโ jobs/
โ โโโ utils/
โ
โโโ scripts/
โ โโโ initialImport.ts
โ โโโ importData.ts
โ โโโ sync.ts
โ โโโ backfill.ts
โ โโโ rebuildEmbeddings.ts
โ
โโโ data/
โ โโโ historical/
โ
โโโ tests/
โ
โโโ .env.example
โโโ package.json
โโโ tsconfig.json
โโโ LICENSE
โโโ README.md
```
---
# ๐๏ธ Database
MongoDB is used as the primary database.
The system stores agricultural market information including:
```text
State
District
Market
Commodity Group
Commodity
Variety
Grade
Arrival Date
Minimum Price
Maximum Price
Modal Price
Arrival Quantity
Unit
Source
Scraped Date
```
Important collections include:
```text
market_data
markets
rag_documents
ingestion_logs
system_metadata
```
---
# ๐ Duplicate Prevention
The system prevents duplicate records using a deterministic `recordKey`.
The key is generated using important fields such as:
```text
State
+
District
+
Market
+
Commodity
+
Variety
+
Grade
+
Arrival Date
```
These values are normalized and hashed using **SHA-256**.
MongoDB maintains a unique index on `recordKey`.
Therefore, if the same data is imported again:
```text
Existing Record
โ
โผ
Same recordKey
โ
โผ
Duplicate Detected
โ
โผ
Record Skipped
```
This makes the ingestion process **idempotent**.
---
# ๐ฅ Data Ingestion
The project supports multiple ingestion methods.
### Historical Data
Historical agricultural data can be imported from CSV files.
```text
CSV Files
โ
Validation
โ
Normalization
โ
Duplicate Check
โ
MongoDB
โ
RAG Documents
โ
Embeddings
```
### Daily Data
New market data can be collected using Playwright.
The daily synchronization process:
```text
Scheduled Job
โ
Determine New Date
โ
Open AGMARKNET
โ
Apply Filters
โ
Collect Market Data
โ
Validate & Normalize
โ
Duplicate Check
โ
Store in MongoDB
โ
Generate RAG Documents
โ
Generate Embeddings
```
---
# โฐ Automatic Daily Synchronization
The project uses **node-cron** for scheduled data synchronization.
The scheduler can run the synchronization process automatically at a configured time.
Example:
```env
DATA_SYNC_CRON=0 21 * * *
```
This represents a daily scheduled execution at **9:00 PM**.
If new data is available, it is inserted into MongoDB.
If no new data is available, the system skips the operation instead of generating fake records.
---
# ๐ง RAG Implementation
The project uses **Retrieval-Augmented Generation (RAG)** for semantic search.
The process is:
```text
Market Data
โ
RAG Document
โ
Embedding Generation
โ
Vector Storage
โ
User Question
โ
Question Embedding
โ
Similarity Search
โ
Relevant Documents
โ
AI Response
```
RAG is mainly useful for open-ended questions and contextual searches.
For exact numerical questions, structured MongoDB queries are preferred.
---
# ๐ข Embeddings
Embeddings represent textual information as numerical vectors.
Example:
```text
"Wheat price in Anand"
โ
Embedding Model
โ
[0.12, 0.45, 0.21, ...]
```
The project supports local embedding generation and can also be configured to use an external embedding provider.
---
# ๐ Vector Search
The system can perform semantic similarity search using vector embeddings.
Two modes are supported:
```text
Local Cosine Similarity
OR
MongoDB Atlas Vector Search
```
This allows questions with different wording to retrieve related agricultural information.
---
# ๐ค MCP Tools
The MCP server provides tools such as:
| Tool | Purpose |
| -------------------------- | --------------------------------------- |
| `get_daily_market_data` | Get market data for a particular date |
| `get_district_market_data` | Get district-level data |
| `get_state_market_data` | Get Gujarat-wide data |
| `get_market_data` | Get data for a particular market |
| `get_commodity_price` | Get commodity price statistics |
| `get_price_trend` | Get historical price trends |
| `get_market_list` | Get available markets |
| `search_market_knowledge` | Perform RAG-based semantic search |
| `get_market_summary` | Generate market summary |
| `get_data_source_status` | Check data synchronization status |
| `get_market_comparison` | Compare commodity prices across markets |
All tools validate their input and return structured responses.
---
# ๐ MCP Resources
The server provides read-only MCP resources such as:
```text
agmarknet://gujarat/market-data
agmarknet://gujarat/markets
agmarknet://gujarat/commodities
agmarknet://gujarat/data-status
agmarknet://gujarat/rag-knowledge
```
---
# ๐ฌ MCP Prompts
The project also provides reusable MCP prompts:
```text
analyze_market_trend
generate_market_report
ask_agmarknet_rag
```
These prompts help an AI client perform common agricultural market analysis tasks.
---
# ๐ REST API
The system provides REST endpoints through Express.js.
### Health Check
```http
GET /api/health
```
### Daily Market Data
```http
GET /api/market-data/daily
```
### District Data
```http
GET /api/market-data/district/:district
```
### State Data
```http
GET /api/market-data/state
```
### Market Data
```http
GET /api/market-data/market/:market
```
### Commodity Data
```http
GET /api/market-data/commodity/:commodity
```
### Price Trend
```http
GET /api/market-data/trend/:commodity
```
### Market List
```http
GET /api/markets
```
### Data Status
```http
GET /api/data-status
```
### RAG Search
```http
GET /api/rag/search
```
---
# โ๏ธ Installation
## Prerequisites
Install the following:
* Node.js 20+
* MongoDB 6+
* npm
* Git
* Chromium browser for Playwright
---
## 1. Clone Repository
```bash
git clone https://github.com/rashmikaambla/AGMARKNET-MCP-Server.git
```
```bash
cd AGMARKNET-MCP-Server
```
---
## 2. Install Dependencies
```bash
npm install
```
---
## 3. Install Playwright Browser
```bash
npx playwright install chromium
```
---
## 4. Configure Environment
Create `.env` from `.env.example`.
Example:
```env
NODE_ENV=development
PORT=3000
MONGODB_URI=mongodb://127.0.0.1:27017/gujarat_agmarknet
MONGODB_DATABASE=gujarat_agmarknet
MONGODB_VECTOR_INDEX=rag_vector_index
ADMIN_API_KEY=your-secret-key
AGMARKNET_STATE=Gujarat
AGMARKNET_COMMODITY_GROUP=Cereals
AGMARKNET_COMMODITY=Wheat
EMBEDDING_PROVIDER=local
VECTOR_SEARCH_MODE=local
```
---
# โถ๏ธ Running the Project
### Development Server
```bash
npm run dev
```
The REST API will run on:
```text
http://localhost:3000
```
---
### Build Project
```bash
npm run build
```
---
### Start Production Build
```bash
npm start
```
---
### Run MCP Server
```bash
npm run mcp
```
---
### Run Data Synchronization
```bash
npm run sync
```
---
### Import Historical Data
```bash
npm run import-historical
```
---
### Rebuild RAG Embeddings
```bash
npm run rebuild-embeddings
```
---
### Run Tests
```bash
npm test
```
---
# ๐ Connecting with Claude
The MCP server can be connected to an MCP-compatible AI client.
The general workflow is:
```text
Claude
โ
โ MCP
โผ
MCP Server
โ
โผ
Market Data Services
โ
โผ
MongoDB
```
Once connected, the AI client can use the available MCP tools to answer agricultural market questions.
Example:
```text
User:
"What is the wheat price in Anand on 7 September 2026?"
โ
Claude
โ
MCP Tool:
get_daily_market_data
โ
MongoDB
โ
Market Price Data
โ
Claude generates the answer
```
---
# ๐งช MCP Inspector
The MCP server can also be tested using MCP Inspector.
```bash
npx @modelcontextprotocol/inspector npx tsx src/server/mcpServer.ts
```
MCP Inspector can be used to:
* View available tools
* Execute MCP tools
* View resources
* Test prompts
* Validate tool responses
* Test invalid inputs
---
# ๐ก Example Questions
After connecting the server to an AI client, users can ask:
### Basic Queries
```text
What is the wheat price in Anand?
```
```text
Show today's market data for Anand.
```
```text
What was the wheat price yesterday?
```
### Price Analysis
```text
What is the average wheat price in Anand?
```
```text
What is the modal price of wheat?
```
```text
Show the wheat price trend for the last 30 days.
```
### Market Comparison
```text
Compare wheat prices in Anand and Ahmedabad.
```
```text
Compare wheat prices across different Gujarat markets.
```
### Historical Analysis
```text
What was the average wheat price during August 2026?
```
```text
Find historical information about wheat prices in Anand.
```
### Reports
```text
Generate a market report for Anand for the last 30 days.
```
---
# ๐ Complete Working Flow
The complete system works as follows:
```text
AGMARKNET
โ
โผ
Playwright
โ
โผ
Data Extraction
โ
โผ
Validation & Normalization
โ
โผ
Duplicate Check
โ
โผ
MongoDB
โ
โโโโโโโโโโโโดโโโโโโโโโโโ
โ โ
โผ โผ
Structured Data RAG Documents
โ
โผ
Embeddings
โ
โผ
Vector Search
โ
โโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โผ โผ
REST API MCP Server
โ
โผ
AI Client
โ
โผ
Natural Language
Answer
```
---
# ๐ก๏ธ Data Reliability
The system follows several mechanisms to maintain data reliability:
* Input validation
* Data normalization
* Duplicate detection
* Unique MongoDB indexes
* Structured error handling
* Source identification
* Ingestion logs
* No fabricated market records
* Historical data preservation
Every market record contains information about its source.
---
# ๐ Data Preservation
Historical data is stored permanently.
The system does not use a rolling data-retention mechanism for the market data.
New data is appended while previously stored records remain available for historical analysis.
This enables:
* Historical comparison
* Trend analysis
* Market comparison
* RAG retrieval
* Long-term agricultural data analysis
---
# ๐ Security
Administrative ingestion APIs are protected using an API key.
Example:
```http
x-admin-api-key: YOUR_API_KEY
```
Sensitive configuration such as:
```text
MONGODB_URI
ADMIN_API_KEY
API Keys
```
should be stored in `.env` and should **not** be committed to GitHub.
---
# ๐งช Testing
The project includes unit and integration tests.
Testing covers areas such as:
* Validation
* Date utilities
* Data normalization
* CSV processing
* Market data logic
* Ingestion
* RAG functionality
* MongoDB repositories
* Duplicate prevention
Run:
```bash
npm test
```
---
# โ ๏ธ Limitations
* AGMARKNET website structure can change over time.
* Playwright selectors may need to be updated if the website UI changes.
* Local vector search is suitable for a college/project-scale dataset.
* Local embeddings are simpler than transformer-based embeddings.
* Availability of historical data depends on the source website.
* Internet connectivity is required for live data collection.
---
# ๐ฎ Future Scope
Possible future improvements include:
* ๐พ Support for additional Indian states
* ๐ฑ Mobile/web dashboard
* ๐ Advanced market analytics
* ๐ Interactive price charts
* ๐ค Neural embedding models
* ๐ฎ Machine-learning-based price forecasting
* โ๏ธ Cloud deployment
* ๐๏ธ MongoDB Atlas Vector Search
* ๐จ Automated scraper failure alerts
* ๐ Automated agricultural market reports
* ๐ Multilingual support including Gujarati
* ๐๏ธ Voice-based agricultural market queries
---
# ๐ Academic Project
This project demonstrates the practical use of:
* Artificial Intelligence
* Generative AI
* Model Context Protocol
* Retrieval-Augmented Generation
* Web Automation
* Database Management
* REST API Development
* Vector Search
* Natural Language Querying
* Data Engineering
It combines these technologies into a single agricultural market intelligence system.
---
# ๐ฉโ๐ป Developer
**Rashmika Ambla**
B.Tech โ Agricultural Information Technology
GitHub:
https://github.com/rashmikaambla
Project Repository:
https://github.com/rashmikaambla/AGMARKNET-MCP-Server
---
# ๐ License
This project is licensed under the **MIT License**.
---
## โญ Project Summary
> **Gujarat AGMARKNET MCP Server** is an AI-powered agricultural market intelligence system that collects and permanently stores Gujarat market price and arrival data, provides structured REST APIs and MCP tools, and enables AI applications to answer natural-language agricultural market queries using MongoDB, RAG, embeddings, vector search, and automated data synchronization.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo issues