optioncontext-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from optioncontext_mcp.server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,71 @@
1
+ import os
2
+ import uuid
3
+ import asyncio
4
+ import httpx
5
+ from typing import Dict, Any, Optional
6
+
7
+ class OptionContextClient:
8
+ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None):
9
+ self.base_url = (base_url or os.getenv("OPTIONCONTEXT_BASE_URL") or os.getenv("FASTAPI_BASE_URL") or "https://optioncontext.com").rstrip("/")
10
+ self.default_api_key = api_key or os.getenv("OPTIONCONTEXT_API_KEY")
11
+
12
+ def _resolve_api_key(self, provided_key: Optional[str]) -> str:
13
+ key = provided_key or self.default_api_key
14
+ if not key:
15
+ raise ValueError("API Key is missing. Pass 'api_key' to the tool or set OPTIONCONTEXT_API_KEY in your environment variables.")
16
+ return key
17
+
18
+ async def _request_with_retry(self, endpoint: str, params: Dict[str, Any], api_key: Optional[str], requires_auth: bool = True, max_attempts: int = 3) -> str:
19
+ url = f"{self.base_url}{endpoint}"
20
+ headers = {"X-Idempotency-Key": str(uuid.uuid4())}
21
+
22
+ if requires_auth:
23
+ headers["X-Agent-API-Key"] = self._resolve_api_key(api_key)
24
+
25
+ for attempt in range(max_attempts):
26
+ try:
27
+ async with httpx.AsyncClient() as client:
28
+ response = await client.get(url, headers=headers, params=params, timeout=15.0)
29
+ if response.status_code == 200:
30
+ try:
31
+ data = response.json()
32
+ if data.get("status") in ("PENDING", "loading") and attempt < max_attempts - 1:
33
+ await asyncio.sleep(4.0)
34
+ continue
35
+ except ValueError:
36
+ pass
37
+ return response.text
38
+ elif response.status_code == 403:
39
+ return f"Forbidden (403): Access Denied. Historical data requires a Plan B subscription."
40
+ elif response.status_code == 401:
41
+ return f"Unauthorized (401): Invalid or expired API credentials."
42
+ else:
43
+ return f"Error {response.status_code}: {response.text}"
44
+ except Exception as e:
45
+ if attempt < max_attempts - 1:
46
+ await asyncio.sleep(4.0)
47
+ continue
48
+ return f"Error connecting to OptionContext gateway: {str(e)}"
49
+ return "Error: Request timed out after multiple retries."
50
+
51
+ async def suggest_symbols(self, query: str) -> str:
52
+ return await self._request_with_retry("/api/suggest-symbols", {"query": query}, api_key=None, requires_auth=False)
53
+
54
+ async def get_market_context(self, symbol: str, expiry: str = "SPOT", asset_type: str = "auto", api_key: Optional[str] = None) -> str:
55
+ params = {"symbol": symbol.upper().strip(), "expiry": expiry.upper().strip()}
56
+ if asset_type and asset_type != "auto":
57
+ params["asset_type"] = asset_type
58
+ return await self._request_with_retry("/api/agent/market-data", params, api_key)
59
+
60
+ async def get_option_chain(self, symbol: str, api_key: Optional[str] = None) -> str:
61
+ params = {"symbol": symbol.upper().strip()}
62
+ return await self._request_with_retry("/api/agent/option-chain", params, api_key)
63
+
64
+ async def get_historical_data(self, symbol: str, from_date: str, to_date: str, interval: str = "ONE_DAY", api_key: Optional[str] = None) -> str:
65
+ params = {
66
+ "symbol": symbol.upper().strip(),
67
+ "from": from_date,
68
+ "to": to_date,
69
+ "interval": interval
70
+ }
71
+ return await self._request_with_retry("/api/agent/historical-data", params, api_key)
@@ -0,0 +1,56 @@
1
+ from mcp.server.fastmcp import FastMCP
2
+ from typing import Optional
3
+ from optioncontext_mcp.client import OptionContextClient
4
+
5
+ mcp = FastMCP("OptionContext MCP Server")
6
+ client = OptionContextClient()
7
+
8
+ @mcp.tool()
9
+ async def suggest_symbols(query: str) -> str:
10
+ """
11
+ Search and resolve correct ticker symbols (e.g. searching 'Reliance' to get 'RELIANCE').
12
+ Args:
13
+ query (str): The search text or company name.
14
+ """
15
+ return await client.suggest_symbols(query)
16
+
17
+ @mcp.tool()
18
+ async def get_market_context(symbol: str, expiry: str = "SPOT", asset_type: str = "auto", api_key: Optional[str] = None) -> str:
19
+ """
20
+ Fetch live quote details, last traded price (LTP), volume, and context for Stocks, Indices, and Futures.
21
+ Args:
22
+ symbol (str): Ticker symbol (e.g. 'NIFTY', 'BANKNIFTY', 'RELIANCE').
23
+ expiry (str): Expiry cycle ('SPOT', 'NEAR', 'FAR', 'NEXT'). Default is 'SPOT'.
24
+ asset_type (str): Asset category ('stock', 'index', 'future', 'auto'). Default is 'auto'.
25
+ api_key (str, optional): API Key. If omitted, uses OPTIONCONTEXT_API_KEY from environment.
26
+ """
27
+ return await client.get_market_context(symbol, expiry, asset_type, api_key)
28
+
29
+ @mcp.tool()
30
+ async def get_option_chain(symbol: str, api_key: Optional[str] = None) -> str:
31
+ """
32
+ Fetch complete option chain matrix including PCR, ATM strike, CE/PE quotes, volume, and Greeks.
33
+ Args:
34
+ symbol (str): Underlying index or stock ticker (e.g. 'NIFTY', 'BANKNIFTY').
35
+ api_key (str, optional): API Key. If omitted, uses OPTIONCONTEXT_API_KEY from environment.
36
+ """
37
+ return await client.get_option_chain(symbol, api_key)
38
+
39
+ @mcp.tool()
40
+ async def get_historical_data(symbol: str, from_date: str, to_date: str, interval: str = "ONE_DAY", api_key: Optional[str] = None) -> str:
41
+ """
42
+ Fetch historical daily/intraday OHLCV candles (Requires Plan B subscription).
43
+ Args:
44
+ symbol (str): Ticker symbol.
45
+ from_date (str): YYYY-MM-DD.
46
+ to_date (str): YYYY-MM-DD.
47
+ interval (str): Candle interval ('ONE_MINUTE', 'FIVE_MINUTE', 'FIFTEEN_MINUTE', 'ONE_DAY'). Default is 'ONE_DAY'.
48
+ api_key (str, optional): API Key.
49
+ """
50
+ return await client.get_historical_data(symbol, from_date, to_date, interval, api_key)
51
+
52
+ def main():
53
+ mcp.run()
54
+
55
+ if __name__ == "__main__":
56
+ main()
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: optioncontext_mcp
3
+ Version: 0.1.0
4
+ Summary: Official Model Context Protocol (MCP) Server for OptionContext Stock and Options Data APIs
5
+ Author-email: OptionContext Team <support@optioncontext.com>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: httpx>=0.25.0
9
+ Requires-Dist: mcp>=1.0.0
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Description-Content-Type: text/markdown
12
+
13
+ # OptionContext MCP Server
14
+
15
+ Official Model Context Protocol (MCP) Server for the OptionContext Stock and Options Data APIs. This premium integration delivers rich analytical and structural data for Indian Stock Markets directly into LLM agents and clients supporting the Model Context Protocol.
16
+
17
+ ## Installation
18
+
19
+ You can install the OptionContext MCP package using `pip`, or run it on-demand with Node and LLM-centric workflows.
20
+
21
+ ### Installation via pip
22
+ ```bash
23
+ pip install optioncontext_mcp
24
+ ```
25
+
26
+ ### Direct Run with npx (Node environment)
27
+ ```bash
28
+ npx -y optioncontext-mcp
29
+ ```
30
+
31
+ ## Configuration
32
+
33
+ To use the OptionContext MCP Server, you must specify your API key and base endpoint URL. You can configure these options via environment variables:
34
+
35
+ - `OPTIONCONTEXT_API_KEY`: Your Agent-as-a-Service API key.
36
+ - `OPTIONCONTEXT_BASE_URL`: The OptionContext endpoint gateway URL (defaults to `https://optioncontext.com` if omitted).
37
+
38
+ For local or custom API gateway environments, `OPTIONCONTEXT_BASE_URL` will fallback automatically to `FASTAPI_BASE_URL` if defined.
39
+
40
+ ## Available Tools
41
+
42
+ The MCP Server exposes the following powerful market analytical tools to any connected client:
43
+
44
+ 1. **`suggest_symbols`**
45
+ - **Description**: Search and resolve correct ticker symbols (e.g., searching 'Reliance' to get 'RELIANCE').
46
+ - **Arguments**:
47
+ - `query` (string): The search text or company name.
48
+
49
+ 2. **`get_market_context`**
50
+ - **Description**: Fetch live quote details, last traded price (LTP), volume, and context for Stocks, Indices, and Futures.
51
+ - **Arguments**:
52
+ - `symbol` (string): Ticker symbol (e.g. 'NIFTY', 'BANKNIFTY', 'RELIANCE').
53
+ - `expiry` (string, optional): Expiry cycle ('SPOT', 'NEAR', 'FAR', 'NEXT'). Default is 'SPOT'.
54
+ - `asset_type` (string, optional): Asset category ('stock', 'index', 'future', 'auto'). Default is 'auto'.
55
+ - `api_key` (string, optional): Override API Key. If omitted, uses environment key.
56
+
57
+ 3. **`get_option_chain`**
58
+ - **Description**: Fetch complete option chain matrix including PCR, ATM strike, CE/PE quotes, volume, and Greeks.
59
+ - **Arguments**:
60
+ - `symbol` (string): Underlying index or stock ticker (e.g. 'NIFTY', 'BANKNIFTY').
61
+ - `api_key` (string, optional): Override API Key. If omitted, uses environment key.
62
+
63
+ 4. **`get_historical_data`**
64
+ - **Description**: Fetch historical daily/intraday OHLCV candles (Requires Plan B subscription).
65
+ - **Arguments**:
66
+ - `symbol` (string): Ticker symbol.
67
+ - `from_date` (string): YYYY-MM-DD.
68
+ - `to_date` (string): YYYY-MM-DD.
69
+ - `interval` (string, optional): Candle interval ('ONE_MINUTE', 'FIVE_MINUTE', 'FIFTEEN_MINUTE', 'ONE_DAY'). Default is 'ONE_DAY'.
70
+ - `api_key` (string, optional): Override API Key.
71
+
72
+ ---
73
+
74
+ Disclaimer & Risk Warning:
75
+ - Data Delay: All market prices, quotes, and option chains provided represent the last completed minute (minimum 1-minute delayed feed) and are not real-time tick feeds.
76
+ - Accuracy: Data is provided on an 'as-is' basis without warranties of absolute accuracy or timeliness.
77
+ - No Liability: The service is strictly for analytical/educational purposes. We assume no liability for any trading losses or investment decisions.
78
+ - Regulatory Risk Disclosure: Trading in derivatives (options and futures) involves high risk. Past performance is not indicative of future results.
@@ -0,0 +1,8 @@
1
+ optioncontext_mcp/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ optioncontext_mcp/__main__.py,sha256=DwPKwiKaN11ovaXcHQbfAkg8HTmqM15DzHSDLdiuAyU,81
3
+ optioncontext_mcp/client.py,sha256=DrnQ456KFd-1ErTXnQ94FTk_-GMRgpHK8tE5s_m4y6s,3719
4
+ optioncontext_mcp/server.py,sha256=a__4tmMKObw0avQ4t8iH9Y9N99qe8_HSZ8LV1UcBVms,2344
5
+ optioncontext_mcp-0.1.0.dist-info/METADATA,sha256=d-WCJT07nk2mrH6lLcyUjt-j7Y_JJ9EShZs-mxfjaZ4,3758
6
+ optioncontext_mcp-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ optioncontext_mcp-0.1.0.dist-info/entry_points.txt,sha256=NHqscrGVcONgotIjO5czgstIJeQt2PPADEDD-iAu_dk,68
8
+ optioncontext_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ optioncontext-mcp = optioncontext_mcp.server:main