tsetmc-mcp 0.1.0__tar.gz
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.
- tsetmc_mcp-0.1.0/.github/ISSUE_TEMPLATE/bug_report.yml +42 -0
- tsetmc_mcp-0.1.0/.github/ISSUE_TEMPLATE/config.yml +5 -0
- tsetmc_mcp-0.1.0/.github/banner.png +0 -0
- tsetmc_mcp-0.1.0/.github/dependabot.yml +10 -0
- tsetmc_mcp-0.1.0/.github/workflows/ci.yml +22 -0
- tsetmc_mcp-0.1.0/.github/workflows/publish.yml +51 -0
- tsetmc_mcp-0.1.0/.gitignore +6 -0
- tsetmc_mcp-0.1.0/LICENSE +21 -0
- tsetmc_mcp-0.1.0/PKG-INFO +79 -0
- tsetmc_mcp-0.1.0/README.md +53 -0
- tsetmc_mcp-0.1.0/pyproject.toml +54 -0
- tsetmc_mcp-0.1.0/server.json +32 -0
- tsetmc_mcp-0.1.0/src/tsetmc_mcp/__init__.py +5 -0
- tsetmc_mcp-0.1.0/src/tsetmc_mcp/http.py +222 -0
- tsetmc_mcp-0.1.0/src/tsetmc_mcp/markets.py +440 -0
- tsetmc_mcp-0.1.0/src/tsetmc_mcp/registry.py +16 -0
- tsetmc_mcp-0.1.0/src/tsetmc_mcp/server.py +86 -0
- tsetmc_mcp-0.1.0/tests/conftest.py +72 -0
- tsetmc_mcp-0.1.0/tests/fixtures/best_limits.json +59 -0
- tsetmc_mcp-0.1.0/tests/fixtures/client_type_0.json +18 -0
- tsetmc_mcp-0.1.0/tests/fixtures/client_type_1.json +18 -0
- tsetmc_mcp-0.1.0/tests/fixtures/closing_info.json +40 -0
- tsetmc_mcp-0.1.0/tests/fixtures/daily_list.json +118 -0
- tsetmc_mcp-0.1.0/tests/fixtures/index_b1.json +116 -0
- tsetmc_mcp-0.1.0/tests/fixtures/index_b2.json +60 -0
- tsetmc_mcp-0.1.0/tests/fixtures/instrument_info.json +56 -0
- tsetmc_mcp-0.1.0/tests/fixtures/market_overview.json +19 -0
- tsetmc_mcp-0.1.0/tests/fixtures/marketwatch.json +752 -0
- tsetmc_mcp-0.1.0/tests/fixtures/search_foolad.json +80 -0
- tsetmc_mcp-0.1.0/tests/test_live_markets.py +55 -0
- tsetmc_mcp-0.1.0/tests/test_markets.py +194 -0
- tsetmc_mcp-0.1.0/uv.lock +1292 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
name: Bug report
|
|
2
|
+
description: A tool failed or returned wrong data
|
|
3
|
+
labels: [bug]
|
|
4
|
+
body:
|
|
5
|
+
- type: input
|
|
6
|
+
id: tool
|
|
7
|
+
attributes:
|
|
8
|
+
label: Tool
|
|
9
|
+
description: Which tool, e.g. ts_get_quote
|
|
10
|
+
validations:
|
|
11
|
+
required: true
|
|
12
|
+
- type: textarea
|
|
13
|
+
id: input
|
|
14
|
+
attributes:
|
|
15
|
+
label: Arguments and result
|
|
16
|
+
description: The arguments the agent sent and the error or wrong output. Remove anything personal.
|
|
17
|
+
render: json
|
|
18
|
+
validations:
|
|
19
|
+
required: true
|
|
20
|
+
- type: textarea
|
|
21
|
+
id: expected
|
|
22
|
+
attributes:
|
|
23
|
+
label: What you expected
|
|
24
|
+
description: e.g. the price shown on tsetmc.com
|
|
25
|
+
- type: input
|
|
26
|
+
id: client
|
|
27
|
+
attributes:
|
|
28
|
+
label: MCP client and OS
|
|
29
|
+
placeholder: Claude Desktop 1.x on Windows 11
|
|
30
|
+
- type: dropdown
|
|
31
|
+
id: network
|
|
32
|
+
attributes:
|
|
33
|
+
label: Network
|
|
34
|
+
options:
|
|
35
|
+
- Direct connection
|
|
36
|
+
- VPN or proxy
|
|
37
|
+
- TSETMC_MCP_PROXY set
|
|
38
|
+
- type: input
|
|
39
|
+
id: version
|
|
40
|
+
attributes:
|
|
41
|
+
label: tsetmc-mcp version
|
|
42
|
+
placeholder: "0.1.0"
|
|
Binary file
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python: ["3.10", "3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v7
|
|
16
|
+
- uses: astral-sh/setup-uv@v10.2.0
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python }}
|
|
19
|
+
- run: uv sync --locked
|
|
20
|
+
- run: uv run ruff check .
|
|
21
|
+
- run: uv run ruff format --check .
|
|
22
|
+
- run: uv run pytest -q
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
name: Publish
|
|
2
|
+
|
|
3
|
+
# Tag a release (git tag v0.1.0 && git push --tags) after bumping the version in
|
|
4
|
+
# pyproject.toml and server.json.
|
|
5
|
+
on:
|
|
6
|
+
push:
|
|
7
|
+
tags: ["v*"]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
pypi:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
environment: pypi
|
|
13
|
+
permissions:
|
|
14
|
+
id-token: write # PyPI trusted publishing
|
|
15
|
+
contents: write # GitHub Release
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v7
|
|
18
|
+
- uses: astral-sh/setup-uv@v10.2.0
|
|
19
|
+
- name: Check versions match the tag
|
|
20
|
+
run: |
|
|
21
|
+
TAG=${GITHUB_REF_NAME#v}
|
|
22
|
+
grep -q "^version = \"$TAG\"" pyproject.toml
|
|
23
|
+
test "$(jq -r .version server.json)" = "$TAG"
|
|
24
|
+
test "$(jq -r '.packages[0].version' server.json)" = "$TAG"
|
|
25
|
+
- run: uv sync --locked && uv run pytest -q
|
|
26
|
+
- run: uv build
|
|
27
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
28
|
+
- run: gh release create "$GITHUB_REF_NAME" dist/* --generate-notes --title "$GITHUB_REF_NAME"
|
|
29
|
+
env:
|
|
30
|
+
GH_TOKEN: ${{ github.token }}
|
|
31
|
+
|
|
32
|
+
mcp-registry:
|
|
33
|
+
needs: pypi
|
|
34
|
+
runs-on: ubuntu-latest
|
|
35
|
+
permissions:
|
|
36
|
+
id-token: write # MCP Registry login via GitHub OIDC
|
|
37
|
+
contents: read
|
|
38
|
+
steps:
|
|
39
|
+
- uses: actions/checkout@v7
|
|
40
|
+
- name: Wait for PyPI to serve the new version
|
|
41
|
+
run: |
|
|
42
|
+
for i in $(seq 1 30); do
|
|
43
|
+
curl -sf "https://pypi.org/pypi/tsetmc-mcp/${GITHUB_REF_NAME#v}/json" >/dev/null && exit 0
|
|
44
|
+
sleep 10
|
|
45
|
+
done
|
|
46
|
+
exit 1
|
|
47
|
+
- name: Install mcp-publisher
|
|
48
|
+
run: |
|
|
49
|
+
curl -L "https://github.com/modelcontextprotocol/registry/releases/download/v1.8.1/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher
|
|
50
|
+
- run: ./mcp-publisher login github-oidc
|
|
51
|
+
- run: ./mcp-publisher publish
|
tsetmc_mcp-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sepehr Radmard
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tsetmc-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Unofficial read-only MCP server for the Tehran Stock Exchange (tsetmc.com): quotes, market movers, order book, history, indices.
|
|
5
|
+
Project-URL: Homepage, https://github.com/sepehr071/tsetmc-mcp
|
|
6
|
+
Project-URL: Issues, https://github.com/sepehr071/tsetmc-mcp/issues
|
|
7
|
+
Author-email: Sepehr Radmard <sepehrr80@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: bourse,iran,mcp,model-context-protocol,stocks,tehran-stock-exchange,tse,tsetmc
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: curl-cffi>=0.16.3
|
|
22
|
+
Requires-Dist: httpx-curl-cffi>=0.1.5
|
|
23
|
+
Requires-Dist: httpx>=0.27
|
|
24
|
+
Requires-Dist: mcp<3,>=2.2
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
<!-- mcp-name: io.github.sepehr071/tsetmc-mcp -->
|
|
28
|
+
|
|
29
|
+
<div align="center">
|
|
30
|
+
|
|
31
|
+
<img src="https://raw.githubusercontent.com/sepehr071/tsetmc-mcp/main/.github/banner.png" alt="tsetmc-mcp: unofficial TSETMC MCP server for Claude, Cursor and Copilot" width="100%">
|
|
32
|
+
|
|
33
|
+
</div>
|
|
34
|
+
|
|
35
|
+
# tsetmc-mcp: Tehran Stock Exchange MCP server for AI agents
|
|
36
|
+
|
|
37
|
+
An unofficial, read-only MCP server for [TSETMC](https://tsetmc.com) (مدیریت فناوری بورس تهران), the Tehran Stock Exchange
|
|
38
|
+
and Iran Fara Bourse data portal: quotes, top movers, order book, daily history, real vs legal trading and indices.
|
|
39
|
+
|
|
40
|
+
## For AI agents
|
|
41
|
+
|
|
42
|
+
- **What:** unofficial MCP server for tsetmc.com market data. Persian queries work for symbol search (Arabic ي/ك are accepted).
|
|
43
|
+
- **Install:** `uvx tsetmc-mcp` or `claude mcp add tsetmc -- uvx tsetmc-mcp`. Transport: stdio. Needs [uv](https://docs.astral.sh/uv/getting-started/installation/) (Python 3.10+).
|
|
44
|
+
- **Auth:** none. Optional `TSETMC_MCP_PROXY` (HTTP proxy URL, or a comma-separated list); system proxy settings are ignored.
|
|
45
|
+
- **Access:** read-only, so no confirmation is needed before calling any tool.
|
|
46
|
+
- **Tools:** 8, all prefixed `ts_`. Typical sequence: `ts_indices` -> `ts_market_movers` -> `ts_get_quote` -> `ts_price_history`.
|
|
47
|
+
- **Output:** compact JSON. Prices are in **Rial** (Toman = Rial / 10), volumes in shares, dates Gregorian.
|
|
48
|
+
- **Network:** tsetmc.com only answers some networks. If you get HTTP 403, try an Iranian connection or set `TSETMC_MCP_PROXY`.
|
|
49
|
+
- **Machine-readable:** [`server.json`](server.json).
|
|
50
|
+
|
|
51
|
+
## Tools
|
|
52
|
+
|
|
53
|
+
| Tool | Purpose |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `ts_search_symbols` | Find Tehran Stock Exchange instruments (shares, funds, rights, bonds) by ticker or name |
|
|
56
|
+
| `ts_get_quote` | Latest price, daily range, volume and key facts of one instrument on the Tehran Stock Exchange |
|
|
57
|
+
| `ts_market_movers` | Top traded instruments of a market today, ranked by gain, loss, volume, value or trade count |
|
|
58
|
+
| `ts_order_book` | Best five bid and ask levels (price, volume, order count) of one instrument |
|
|
59
|
+
| `ts_price_history` | Daily open, high, low, close, volume, trades and value of one instrument for its latest trading days, newest first |
|
|
60
|
+
| `ts_real_legal` | Buy and sell volume, value and buyer/seller counts split by real (individual) and legal (institutional) traders per day |
|
|
61
|
+
| `ts_indices` | TSE total index, market state and trading totals, plus every sector and market index with its change |
|
|
62
|
+
| `ts_index_history` | Daily close, high, low and percent change of a TSE index (total, equal-weight, sector...), newest first |
|
|
63
|
+
|
|
64
|
+
## Reply size
|
|
65
|
+
|
|
66
|
+
Every reply stays under about 15 KB: `ts_market_movers` returns at most 30 rows, `ts_price_history` 50 days, `ts_index_history` 100 days, `ts_real_legal` 10 days.
|
|
67
|
+
The order book is empty outside trading hours (Saturday to Wednesday mornings); other tools then show the last session.
|
|
68
|
+
|
|
69
|
+
## Development
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uv sync
|
|
73
|
+
uv run ruff check . && uv run ruff format --check .
|
|
74
|
+
uv run python -m pytest -q # offline unit tests
|
|
75
|
+
uv run python -m pytest -m live -q # calls tsetmc.com
|
|
76
|
+
uv build
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Not affiliated with TSETMC. Data is informational and may be delayed; not financial advice. MIT license.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
<!-- mcp-name: io.github.sepehr071/tsetmc-mcp -->
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
<img src="https://raw.githubusercontent.com/sepehr071/tsetmc-mcp/main/.github/banner.png" alt="tsetmc-mcp: unofficial TSETMC MCP server for Claude, Cursor and Copilot" width="100%">
|
|
6
|
+
|
|
7
|
+
</div>
|
|
8
|
+
|
|
9
|
+
# tsetmc-mcp: Tehran Stock Exchange MCP server for AI agents
|
|
10
|
+
|
|
11
|
+
An unofficial, read-only MCP server for [TSETMC](https://tsetmc.com) (مدیریت فناوری بورس تهران), the Tehran Stock Exchange
|
|
12
|
+
and Iran Fara Bourse data portal: quotes, top movers, order book, daily history, real vs legal trading and indices.
|
|
13
|
+
|
|
14
|
+
## For AI agents
|
|
15
|
+
|
|
16
|
+
- **What:** unofficial MCP server for tsetmc.com market data. Persian queries work for symbol search (Arabic ي/ك are accepted).
|
|
17
|
+
- **Install:** `uvx tsetmc-mcp` or `claude mcp add tsetmc -- uvx tsetmc-mcp`. Transport: stdio. Needs [uv](https://docs.astral.sh/uv/getting-started/installation/) (Python 3.10+).
|
|
18
|
+
- **Auth:** none. Optional `TSETMC_MCP_PROXY` (HTTP proxy URL, or a comma-separated list); system proxy settings are ignored.
|
|
19
|
+
- **Access:** read-only, so no confirmation is needed before calling any tool.
|
|
20
|
+
- **Tools:** 8, all prefixed `ts_`. Typical sequence: `ts_indices` -> `ts_market_movers` -> `ts_get_quote` -> `ts_price_history`.
|
|
21
|
+
- **Output:** compact JSON. Prices are in **Rial** (Toman = Rial / 10), volumes in shares, dates Gregorian.
|
|
22
|
+
- **Network:** tsetmc.com only answers some networks. If you get HTTP 403, try an Iranian connection or set `TSETMC_MCP_PROXY`.
|
|
23
|
+
- **Machine-readable:** [`server.json`](server.json).
|
|
24
|
+
|
|
25
|
+
## Tools
|
|
26
|
+
|
|
27
|
+
| Tool | Purpose |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `ts_search_symbols` | Find Tehran Stock Exchange instruments (shares, funds, rights, bonds) by ticker or name |
|
|
30
|
+
| `ts_get_quote` | Latest price, daily range, volume and key facts of one instrument on the Tehran Stock Exchange |
|
|
31
|
+
| `ts_market_movers` | Top traded instruments of a market today, ranked by gain, loss, volume, value or trade count |
|
|
32
|
+
| `ts_order_book` | Best five bid and ask levels (price, volume, order count) of one instrument |
|
|
33
|
+
| `ts_price_history` | Daily open, high, low, close, volume, trades and value of one instrument for its latest trading days, newest first |
|
|
34
|
+
| `ts_real_legal` | Buy and sell volume, value and buyer/seller counts split by real (individual) and legal (institutional) traders per day |
|
|
35
|
+
| `ts_indices` | TSE total index, market state and trading totals, plus every sector and market index with its change |
|
|
36
|
+
| `ts_index_history` | Daily close, high, low and percent change of a TSE index (total, equal-weight, sector...), newest first |
|
|
37
|
+
|
|
38
|
+
## Reply size
|
|
39
|
+
|
|
40
|
+
Every reply stays under about 15 KB: `ts_market_movers` returns at most 30 rows, `ts_price_history` 50 days, `ts_index_history` 100 days, `ts_real_legal` 10 days.
|
|
41
|
+
The order book is empty outside trading hours (Saturday to Wednesday mornings); other tools then show the last session.
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
uv sync
|
|
47
|
+
uv run ruff check . && uv run ruff format --check .
|
|
48
|
+
uv run python -m pytest -q # offline unit tests
|
|
49
|
+
uv run python -m pytest -m live -q # calls tsetmc.com
|
|
50
|
+
uv build
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Not affiliated with TSETMC. Data is informational and may be delayed; not financial advice. MIT license.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "tsetmc-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Unofficial read-only MCP server for the Tehran Stock Exchange (tsetmc.com): quotes, market movers, order book, history, indices."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Sepehr Radmard", email = "sepehrr80@gmail.com" }]
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
keywords = ["mcp", "model-context-protocol", "tsetmc", "tehran-stock-exchange", "iran", "stocks", "bourse", "tse"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.10",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"mcp>=2.2,<3",
|
|
24
|
+
"httpx>=0.27",
|
|
25
|
+
"httpx-curl-cffi>=0.1.5",
|
|
26
|
+
"curl-cffi>=0.16.3",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/sepehr071/tsetmc-mcp"
|
|
31
|
+
Issues = "https://github.com/sepehr071/tsetmc-mcp/issues"
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
tsetmc-mcp = "tsetmc_mcp.server:main"
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
dev = ["pytest>=8", "ruff>=0.6"]
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["hatchling"]
|
|
41
|
+
build-backend = "hatchling.build"
|
|
42
|
+
|
|
43
|
+
[tool.pytest.ini_options]
|
|
44
|
+
testpaths = ["tests"]
|
|
45
|
+
addopts = "-m 'not live'"
|
|
46
|
+
markers = ["live: calls the real TSETMC APIs (run with -m live)"]
|
|
47
|
+
|
|
48
|
+
[tool.ruff]
|
|
49
|
+
line-length = 120
|
|
50
|
+
target-version = "py310"
|
|
51
|
+
|
|
52
|
+
[tool.ruff.lint]
|
|
53
|
+
select = ["E", "F", "I", "B", "UP"]
|
|
54
|
+
ignore = ["E501"] # long Field(description=...) strings read better on one line
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
|
+
"name": "io.github.sepehr071/tsetmc-mcp",
|
|
4
|
+
"title": "TSETMC Tehran Stock Exchange",
|
|
5
|
+
"description": "Unofficial read-only Tehran Stock Exchange (TSETMC): quotes, movers, order book, history, indices.",
|
|
6
|
+
"repository": {
|
|
7
|
+
"url": "https://github.com/sepehr071/tsetmc-mcp",
|
|
8
|
+
"source": "github"
|
|
9
|
+
},
|
|
10
|
+
"websiteUrl": "https://github.com/sepehr071/tsetmc-mcp",
|
|
11
|
+
"version": "0.1.0",
|
|
12
|
+
"packages": [
|
|
13
|
+
{
|
|
14
|
+
"registryType": "pypi",
|
|
15
|
+
"registryBaseUrl": "https://pypi.org",
|
|
16
|
+
"identifier": "tsetmc-mcp",
|
|
17
|
+
"version": "0.1.0",
|
|
18
|
+
"runtimeHint": "uvx",
|
|
19
|
+
"transport": {
|
|
20
|
+
"type": "stdio"
|
|
21
|
+
},
|
|
22
|
+
"environmentVariables": [
|
|
23
|
+
{
|
|
24
|
+
"name": "TSETMC_MCP_PROXY",
|
|
25
|
+
"description": "Optional HTTP proxy URL for tsetmc.com requests; system proxy settings are ignored. Also accepts a comma-separated list: one is used until it gets blocked or fails to connect, then the next.",
|
|
26
|
+
"isRequired": false,
|
|
27
|
+
"isSecret": false
|
|
28
|
+
}
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
]
|
|
32
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Shared async HTTP client for the TSETMC (Tehran Stock Exchange) market-data endpoints.
|
|
2
|
+
|
|
3
|
+
Every tool goes through `fetch`, which caps concurrency and turns HTTP failures
|
|
4
|
+
into `ToolError` messages the model can act on.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import copy
|
|
11
|
+
import json as json_lib
|
|
12
|
+
import os
|
|
13
|
+
import random
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
from curl_cffi.const import CurlOpt
|
|
19
|
+
from httpx_curl_cffi import AsyncCurlTransport
|
|
20
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
21
|
+
|
|
22
|
+
API = "https://cdn.tsetmc.com/api"
|
|
23
|
+
|
|
24
|
+
HEADERS = {
|
|
25
|
+
# User-Agent, sec-ch-ua and TLS come from the impersonated Chrome profile (see _get_client).
|
|
26
|
+
"Accept": "application/json",
|
|
27
|
+
"Accept-Language": "fa-IR,fa;q=0.9,en;q=0.8",
|
|
28
|
+
"sec-fetch-dest": "empty",
|
|
29
|
+
"sec-fetch-mode": "cors",
|
|
30
|
+
"priority": "u=1, i",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
MAX_CONCURRENCY = 2
|
|
34
|
+
JITTER = (0.1, 0.4) # seconds before each uncached call
|
|
35
|
+
MAX_RETRIES = 2
|
|
36
|
+
MAX_RETRY_WAIT = 10 # cap for Retry-After and backoff, seconds
|
|
37
|
+
CACHE_TTL = 15 # seconds; live prices must stay fresh
|
|
38
|
+
CACHE_MAX = 64
|
|
39
|
+
RETRY_DELAY = 0.5 # seconds, doubled per retry
|
|
40
|
+
MAX_BODY = 5_000_000 # bytes; larger responses are refused (the whole-market watch is ~1 MB, index history ~0.6 MB)
|
|
41
|
+
HOSTS = {"cdn.tsetmc.com"}
|
|
42
|
+
SITE = "https://main.tsetmc.com"
|
|
43
|
+
|
|
44
|
+
_transport: httpx.AsyncBaseTransport | None = None
|
|
45
|
+
_client: httpx.AsyncClient | None = None
|
|
46
|
+
_limit: asyncio.Semaphore | None = None
|
|
47
|
+
_proxy_index = 0
|
|
48
|
+
_retired: set[asyncio.Task] = set()
|
|
49
|
+
_cache: dict[tuple, tuple[float, Any]] = {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _XhrTransport(AsyncCurlTransport):
|
|
53
|
+
"""The Chrome profile sends navigation-only headers; a None value makes curl drop them (API calls are XHR)."""
|
|
54
|
+
|
|
55
|
+
def _create_request_params(self, req: httpx.Request) -> dict[str, Any]:
|
|
56
|
+
p = super()._create_request_params(req)
|
|
57
|
+
p["headers"] = [*p["headers"], (b"upgrade-insecure-requests", None), (b"sec-fetch-user", None)]
|
|
58
|
+
return p
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ApiError(ToolError):
|
|
62
|
+
"""A failed upstream call. `status` is the HTTP status, or None for network errors."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, message: str, status: int | None = None):
|
|
65
|
+
super().__init__(message)
|
|
66
|
+
self.status = status
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def set_transport(transport: httpx.AsyncBaseTransport | None) -> None:
|
|
70
|
+
"""Swap the transport (tests use httpx.MockTransport). Drops the current client."""
|
|
71
|
+
global _transport, _client, _limit, _proxy_index
|
|
72
|
+
_transport, _client, _limit, _proxy_index = transport, None, None, 0
|
|
73
|
+
_cache.clear()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _proxies() -> list[str]:
|
|
77
|
+
"""TSETMC_MCP_PROXY: one proxy URL, or a comma-separated list used one at a time."""
|
|
78
|
+
return [p.strip() for p in os.environ.get("TSETMC_MCP_PROXY", "").split(",") if p.strip()]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _next_proxy(client: httpx.AsyncClient) -> None:
|
|
82
|
+
"""Sticky pool: move to the next proxy after a block or connect error; the next call rebuilds the client.
|
|
83
|
+
|
|
84
|
+
Only the client that failed may rotate. The old client is closed late because other requests may still use it.
|
|
85
|
+
"""
|
|
86
|
+
global _client, _limit, _proxy_index
|
|
87
|
+
if len(_proxies()) < 2 or client is not _client:
|
|
88
|
+
return
|
|
89
|
+
_client, _limit, _proxy_index = None, None, _proxy_index + 1
|
|
90
|
+
t = asyncio.create_task(_close_later(client))
|
|
91
|
+
_retired.add(t)
|
|
92
|
+
t.add_done_callback(_retired.discard)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def _close_later(client: httpx.AsyncClient) -> None:
|
|
96
|
+
await asyncio.sleep(30) # longer than the 20 s request timeout
|
|
97
|
+
await client.aclose()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _get_client() -> tuple[httpx.AsyncClient, asyncio.Semaphore]:
|
|
101
|
+
global _client, _limit
|
|
102
|
+
if _client is None:
|
|
103
|
+
# System proxy settings are ignored; the proxy only comes from TSETMC_MCP_PROXY. curl_cffi presents
|
|
104
|
+
# Chrome's TLS/HTTP2 fingerprint and default headers. The proxy goes to the transport.
|
|
105
|
+
proxies = _proxies()
|
|
106
|
+
_client = httpx.AsyncClient(
|
|
107
|
+
transport=_transport
|
|
108
|
+
or _XhrTransport(
|
|
109
|
+
impersonate="chrome",
|
|
110
|
+
default_headers=True,
|
|
111
|
+
curl_options={
|
|
112
|
+
CurlOpt.NOPROXY: "*"
|
|
113
|
+
}, # httpx-curl-cffi drops its own NOPROXY unless this dict is non-empty
|
|
114
|
+
proxy=proxies[_proxy_index % len(proxies)] if proxies else None,
|
|
115
|
+
max_connections=2 * MAX_CONCURRENCY,
|
|
116
|
+
),
|
|
117
|
+
headers=HEADERS,
|
|
118
|
+
timeout=httpx.Timeout(20, connect=5),
|
|
119
|
+
limits=httpx.Limits(max_connections=2 * MAX_CONCURRENCY),
|
|
120
|
+
follow_redirects=False,
|
|
121
|
+
trust_env=False,
|
|
122
|
+
)
|
|
123
|
+
_limit = asyncio.Semaphore(MAX_CONCURRENCY)
|
|
124
|
+
assert _limit is not None
|
|
125
|
+
return _client, _limit
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def fetch(url: str, params: dict[str, Any] | None = None) -> Any:
|
|
129
|
+
"""GET an endpoint and return the parsed JSON body.
|
|
130
|
+
|
|
131
|
+
Retried up to MAX_RETRIES times on timeout, network error, 5xx or 429, with jittered exponential
|
|
132
|
+
backoff or after Retry-After when sent. 403 is never retried.
|
|
133
|
+
"""
|
|
134
|
+
query = dict(params or {})
|
|
135
|
+
host = httpx.URL(url).host
|
|
136
|
+
if host not in HOSTS:
|
|
137
|
+
raise ApiError(f"Refusing to call unexpected host {host}.")
|
|
138
|
+
key = (url, tuple(sorted(query.items())))
|
|
139
|
+
if (hit := _cache.get(key)) and time.monotonic() - hit[0] < CACHE_TTL:
|
|
140
|
+
return copy.deepcopy(hit[1])
|
|
141
|
+
headers = {"Referer": f"{SITE}/", "Origin": SITE, "sec-fetch-site": "same-site"}
|
|
142
|
+
for attempt in range(MAX_RETRIES + 1):
|
|
143
|
+
last = attempt == MAX_RETRIES
|
|
144
|
+
wait = RETRY_DELAY * 2**attempt * random.uniform(1, 1.5)
|
|
145
|
+
try:
|
|
146
|
+
r, content = await _request(url, query, headers, host)
|
|
147
|
+
except ApiError as e:
|
|
148
|
+
if last or e.status is not None:
|
|
149
|
+
raise
|
|
150
|
+
await asyncio.sleep(min(wait, MAX_RETRY_WAIT))
|
|
151
|
+
continue
|
|
152
|
+
if (r.status_code == 429 or r.status_code >= 500) and not last:
|
|
153
|
+
await asyncio.sleep(min(_retry_after(r) or wait, MAX_RETRY_WAIT))
|
|
154
|
+
continue
|
|
155
|
+
break
|
|
156
|
+
|
|
157
|
+
if r.status_code >= 400:
|
|
158
|
+
raise ApiError(_status_message(r, host), r.status_code)
|
|
159
|
+
try:
|
|
160
|
+
body = json_lib.loads(content)
|
|
161
|
+
except ValueError as e:
|
|
162
|
+
raise ApiError(f"{host} returned a non-JSON response (HTTP {r.status_code}).", r.status_code) from e
|
|
163
|
+
if len(_cache) >= CACHE_MAX:
|
|
164
|
+
_cache.pop(next(iter(_cache)))
|
|
165
|
+
_cache[key] = (time.monotonic(), copy.deepcopy(body))
|
|
166
|
+
return body
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def _send(client, limit, url, query, headers, host) -> tuple[httpx.Response, bytes]:
|
|
170
|
+
try:
|
|
171
|
+
async with limit:
|
|
172
|
+
await asyncio.sleep(random.uniform(*JITTER))
|
|
173
|
+
async with client.stream("GET", url, params=query, headers=headers) as r:
|
|
174
|
+
return r, await _read_capped(r, host)
|
|
175
|
+
except httpx.TimeoutException as e:
|
|
176
|
+
raise ApiError(f"{host} did not answer in time. Try again in a moment.") from e
|
|
177
|
+
except httpx.RequestError as e:
|
|
178
|
+
if isinstance(e, httpx.ConnectError | httpx.ProxyError):
|
|
179
|
+
_next_proxy(client)
|
|
180
|
+
raise ApiError(
|
|
181
|
+
f"Could not reach {host} ({type(e).__name__}). Check the internet connection "
|
|
182
|
+
"(or the TSETMC_MCP_PROXY setting if you use one)."
|
|
183
|
+
) from e
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
async def _request(url, query, headers, host) -> tuple[httpx.Response, bytes]:
|
|
187
|
+
client, limit = _get_client()
|
|
188
|
+
r, content = await _send(client, limit, url, query, headers, host)
|
|
189
|
+
if r.status_code in (403, 429):
|
|
190
|
+
_next_proxy(client) # blocked: try the next proxy on the following call
|
|
191
|
+
return r, content
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
async def _read_capped(r: httpx.Response, host: str) -> bytes:
|
|
195
|
+
"""Read the body, refusing anything over MAX_BODY so one huge answer cannot flood memory or context."""
|
|
196
|
+
buf = bytearray()
|
|
197
|
+
async for chunk in r.aiter_bytes():
|
|
198
|
+
buf += chunk
|
|
199
|
+
if len(buf) > MAX_BODY:
|
|
200
|
+
raise ApiError(f"{host} sent a response over {MAX_BODY // 1_000_000} MB; refused.", r.status_code)
|
|
201
|
+
return bytes(buf)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _retry_after(r: httpx.Response) -> float | None:
|
|
205
|
+
"""Seconds from a numeric Retry-After on a 429/503, else None (HTTP-date form is ignored)."""
|
|
206
|
+
v = r.headers.get("retry-after", "")
|
|
207
|
+
return float(v) if r.status_code in (429, 503) and v.replace(".", "", 1).isdigit() else None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _status_message(r: httpx.Response, host: str) -> str:
|
|
211
|
+
code = r.status_code
|
|
212
|
+
if code == 403:
|
|
213
|
+
return f"{host} blocked the request (HTTP 403). The site only serves some networks (Iranian lines work best): try another network or set TSETMC_MCP_PROXY."
|
|
214
|
+
if code == 429:
|
|
215
|
+
return f"{host} is rate limiting requests (HTTP 429). Wait a minute before retrying."
|
|
216
|
+
if code == 500:
|
|
217
|
+
return (
|
|
218
|
+
f"{host} answered HTTP 500: usually an unknown instrument code. Use ts_search_symbols to find the symbol."
|
|
219
|
+
)
|
|
220
|
+
if code >= 500:
|
|
221
|
+
return f"{host} had a server error (HTTP {code}). Try again later."
|
|
222
|
+
return f"{host} rejected the request (HTTP {code})."
|