parallel-variable-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.
- parallel_variable_mcp-0.1.0/LICENSE +21 -0
- parallel_variable_mcp-0.1.0/PKG-INFO +147 -0
- parallel_variable_mcp-0.1.0/README.md +124 -0
- parallel_variable_mcp-0.1.0/pyproject.toml +40 -0
- parallel_variable_mcp-0.1.0/setup.cfg +4 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp/__init__.py +4 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp/__main__.py +6 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp/client.py +271 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp/server.py +661 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp.egg-info/PKG-INFO +147 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp.egg-info/SOURCES.txt +13 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp.egg-info/dependency_links.txt +1 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp.egg-info/entry_points.txt +2 -0
- parallel_variable_mcp-0.1.0/src/parallel_variable_mcp.egg-info/top_level.txt +1 -0
- parallel_variable_mcp-0.1.0/tests/test_mcp_server.py +384 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Parallel Variable (平行变量)
|
|
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,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parallel-variable-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official MCP Server for Parallel Variable (平行变量) — Let real digital residents respond to your ideas.
|
|
5
|
+
Author-email: Parallel Variable Open Platform <open-platform@parallelvariable.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://parallelvariable.com
|
|
8
|
+
Project-URL: Console, https://parallelvariable.com/console
|
|
9
|
+
Project-URL: Documentation, https://parallelvariable.com/open-platform
|
|
10
|
+
Keywords: mcp,model-context-protocol,parallel-variable,simulation,digital-residents,market-research,policy-simulation
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
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: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# 平行变量 Parallel Variable — Official MCP Server
|
|
25
|
+
|
|
26
|
+
> **平行变量(Parallel Variable)— 让世界,回应你的构想。**
|
|
27
|
+
> **Let the real world respond to your ideas before you launch.**
|
|
28
|
+
|
|
29
|
+
`parallel-variable-mcp` 是「平行变量」开放平台官方开源的 **Model Context Protocol (MCP)** 标准服务端(JSON-RPC 2.0 over stdio,**零第三方依赖**,仅需 Python 3.10+)。
|
|
30
|
+
|
|
31
|
+
通过它,你可以在 **Cursor、Claude Desktop、Antigravity、魔搭(ModelScope)、扣子(Coze)** 等任意支持 MCP 的 AI 客户端中,直接调用真实脱敏城市数字居民样本,在正式发布前对商业定价、门店选址、产品改版、品牌公关或社会公共政策进行低成本高保真前测。
|
|
32
|
+
|
|
33
|
+
- 官网与开放平台:[https://parallelvariable.com](https://parallelvariable.com)
|
|
34
|
+
- 领取 API Key / 管理推演点数:[https://parallelvariable.com/console](https://parallelvariable.com/console)
|
|
35
|
+
- 公开 API 基地址:`https://api.parallelvariable.com`
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 核心特性 / Key Features
|
|
40
|
+
|
|
41
|
+
- **零重依赖、开箱即用**:100% Python 标准库实现,无笨重 SDK 依赖,启动即用。
|
|
42
|
+
- **黑盒安全边界**:仅调用公网 `https://api.parallelvariable.com/api/open-platform/v1/*` 公开接口;API Key 仅通过环境变量读取,绝不写入磁盘或打印到日志。
|
|
43
|
+
- **防误扣费护栏**:`pv_run_simulation` 在工具描述中强制约束 AI 助手在扣费启动前,先向用户展示样本量、步进周期与预估点数消耗并获得明确确认。
|
|
44
|
+
- **异步不阻塞**:启动推演后立即返回 `pipeline_id` 与排队位置,随时通过 `pv_get_simulation_results` 拉取进度、去重统计、舆情热搜潜质、分龄切片与脱敏居民真实原话。
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 典型场景示例 / Use Cases
|
|
49
|
+
|
|
50
|
+
1. **商业定价与新店前测**:「在朝阳区开一家精品咖啡店,首杯拿铁 19.9 元,抽 100 位 22–40 岁在职女性测 7 天自然到店与真实评价。」
|
|
51
|
+
2. **产品改版与会员提价**:「将内容 App 连续包月从 15 元调整至 22 元,对比不同收入与学历人群的续费与吐槽倾向。」
|
|
52
|
+
3. **品牌公关与社会事件推演**:「某新能源车企因电池续航缩水引发舆论争议,发布不同回应方案后 14 天内的公众态度与热搜潜质变化。」
|
|
53
|
+
4. **公共政策前测(需政企/科研白名单)**:「博物馆取消预约制 / 地铁高峰票价微调,分青/中/银发三代人群观察支持率与行动意愿。」
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 快速安装 / Quick Start
|
|
58
|
+
|
|
59
|
+
### 方式一:本地可编辑安装(推荐)
|
|
60
|
+
```bash
|
|
61
|
+
cd integrations/parallel-variable-mcp
|
|
62
|
+
pip install -e .
|
|
63
|
+
```
|
|
64
|
+
安装后可直接运行命令 `parallel-variable-mcp`。
|
|
65
|
+
|
|
66
|
+
### 方式二:零安装直接以模块运行
|
|
67
|
+
```bash
|
|
68
|
+
PYTHONPATH=integrations/parallel-variable-mcp/src \
|
|
69
|
+
PARALLEL_VARIABLE_API_KEY="pv_sk_your_api_key" \
|
|
70
|
+
python3 -m parallel_variable_mcp
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 环境变量 / Environment Variables
|
|
74
|
+
| 变量名 | 必填 | 默认值 | 说明 |
|
|
75
|
+
|---|---|---|---|
|
|
76
|
+
| `PARALLEL_VARIABLE_API_KEY` | 是 | 无 | 在 [控制台](https://parallelvariable.com/console) 生成的个人/企业 API Key |
|
|
77
|
+
| `PARALLEL_VARIABLE_BASE_URL` | 否 | `https://api.parallelvariable.com` | 开放平台公开 API 基地址 |
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## 客户端一键配置 / Client Configuration
|
|
82
|
+
|
|
83
|
+
### 1. Cursor (`~/.cursor/mcp.json` 或项目 `.cursor/mcp.json`)
|
|
84
|
+
```json
|
|
85
|
+
{
|
|
86
|
+
"mcpServers": {
|
|
87
|
+
"parallel-variable": {
|
|
88
|
+
"command": "parallel-variable-mcp",
|
|
89
|
+
"env": {
|
|
90
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key"
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 2. Claude Desktop (`claude_desktop_config.json`)
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"mcpServers": {
|
|
101
|
+
"parallel-variable": {
|
|
102
|
+
"command": "python3",
|
|
103
|
+
"args": ["-m", "parallel_variable_mcp"],
|
|
104
|
+
"env": {
|
|
105
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key"
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 3. Antigravity / 魔搭(ModelScope)MCP 配置
|
|
113
|
+
```json
|
|
114
|
+
{
|
|
115
|
+
"mcpServers": {
|
|
116
|
+
"parallel-variable": {
|
|
117
|
+
"command": "parallel-variable-mcp",
|
|
118
|
+
"args": [],
|
|
119
|
+
"env": {
|
|
120
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key",
|
|
121
|
+
"PARALLEL_VARIABLE_BASE_URL": "https://api.parallelvariable.com"
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## 7 个标准工具清单 / Available MCP Tools
|
|
131
|
+
|
|
132
|
+
| Tool 名称 | 是否免费 | 说明 |
|
|
133
|
+
|---|---|---|
|
|
134
|
+
| `pv_list_regions` | 免费 | 查询已开放的数字居民区域列表(如 `110105` 北京朝阳) |
|
|
135
|
+
| `pv_get_targeting_options` | 免费 | 查询标准人群定向筛选字典(性别、人群标签、学历、婚姻、收入档位) |
|
|
136
|
+
| `pv_get_account_status` | 免费 | 查询当前推演点数余额、年度点数包、套餐版本、样本/并发上限与政策白名单状态 |
|
|
137
|
+
| `pv_clarify_scenario` | 免费 | 拆解商业或社会构想,返回推荐步进单位/步数、观测目标、推荐最小年龄与能力边界 |
|
|
138
|
+
| `pv_estimate_population` | 免费 | 实时预估指定地区与筛选条件下覆盖的居民人数及防窄化提示 |
|
|
139
|
+
| `pv_run_simulation` | **扣费(需确认)** | 创建并启动推演流水线,立即返回 `pipeline_id` 与排队位置(不阻塞超时) |
|
|
140
|
+
| `pv_get_simulation_results` | 免费 | 随时查询推演进度、去重统计、社会舆情/分龄切片汇总及精选脱敏居民真实原话 |
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 安全与开源协议 / Security & License
|
|
145
|
+
|
|
146
|
+
- **开源协议**:MIT License(见 [LICENSE](./LICENSE))。
|
|
147
|
+
- **隐私与安全**:本仓库仅作为公网 API 的开源黑盒客户端,不包含任何服务端内部逻辑、模型 Prompt 或私有密钥;所有居民反馈均已在平台侧完成三层脱敏,不包含任何真实个人身份信息(PII)。
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# 平行变量 Parallel Variable — Official MCP Server
|
|
2
|
+
|
|
3
|
+
> **平行变量(Parallel Variable)— 让世界,回应你的构想。**
|
|
4
|
+
> **Let the real world respond to your ideas before you launch.**
|
|
5
|
+
|
|
6
|
+
`parallel-variable-mcp` 是「平行变量」开放平台官方开源的 **Model Context Protocol (MCP)** 标准服务端(JSON-RPC 2.0 over stdio,**零第三方依赖**,仅需 Python 3.10+)。
|
|
7
|
+
|
|
8
|
+
通过它,你可以在 **Cursor、Claude Desktop、Antigravity、魔搭(ModelScope)、扣子(Coze)** 等任意支持 MCP 的 AI 客户端中,直接调用真实脱敏城市数字居民样本,在正式发布前对商业定价、门店选址、产品改版、品牌公关或社会公共政策进行低成本高保真前测。
|
|
9
|
+
|
|
10
|
+
- 官网与开放平台:[https://parallelvariable.com](https://parallelvariable.com)
|
|
11
|
+
- 领取 API Key / 管理推演点数:[https://parallelvariable.com/console](https://parallelvariable.com/console)
|
|
12
|
+
- 公开 API 基地址:`https://api.parallelvariable.com`
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 核心特性 / Key Features
|
|
17
|
+
|
|
18
|
+
- **零重依赖、开箱即用**:100% Python 标准库实现,无笨重 SDK 依赖,启动即用。
|
|
19
|
+
- **黑盒安全边界**:仅调用公网 `https://api.parallelvariable.com/api/open-platform/v1/*` 公开接口;API Key 仅通过环境变量读取,绝不写入磁盘或打印到日志。
|
|
20
|
+
- **防误扣费护栏**:`pv_run_simulation` 在工具描述中强制约束 AI 助手在扣费启动前,先向用户展示样本量、步进周期与预估点数消耗并获得明确确认。
|
|
21
|
+
- **异步不阻塞**:启动推演后立即返回 `pipeline_id` 与排队位置,随时通过 `pv_get_simulation_results` 拉取进度、去重统计、舆情热搜潜质、分龄切片与脱敏居民真实原话。
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 典型场景示例 / Use Cases
|
|
26
|
+
|
|
27
|
+
1. **商业定价与新店前测**:「在朝阳区开一家精品咖啡店,首杯拿铁 19.9 元,抽 100 位 22–40 岁在职女性测 7 天自然到店与真实评价。」
|
|
28
|
+
2. **产品改版与会员提价**:「将内容 App 连续包月从 15 元调整至 22 元,对比不同收入与学历人群的续费与吐槽倾向。」
|
|
29
|
+
3. **品牌公关与社会事件推演**:「某新能源车企因电池续航缩水引发舆论争议,发布不同回应方案后 14 天内的公众态度与热搜潜质变化。」
|
|
30
|
+
4. **公共政策前测(需政企/科研白名单)**:「博物馆取消预约制 / 地铁高峰票价微调,分青/中/银发三代人群观察支持率与行动意愿。」
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 快速安装 / Quick Start
|
|
35
|
+
|
|
36
|
+
### 方式一:本地可编辑安装(推荐)
|
|
37
|
+
```bash
|
|
38
|
+
cd integrations/parallel-variable-mcp
|
|
39
|
+
pip install -e .
|
|
40
|
+
```
|
|
41
|
+
安装后可直接运行命令 `parallel-variable-mcp`。
|
|
42
|
+
|
|
43
|
+
### 方式二:零安装直接以模块运行
|
|
44
|
+
```bash
|
|
45
|
+
PYTHONPATH=integrations/parallel-variable-mcp/src \
|
|
46
|
+
PARALLEL_VARIABLE_API_KEY="pv_sk_your_api_key" \
|
|
47
|
+
python3 -m parallel_variable_mcp
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 环境变量 / Environment Variables
|
|
51
|
+
| 变量名 | 必填 | 默认值 | 说明 |
|
|
52
|
+
|---|---|---|---|
|
|
53
|
+
| `PARALLEL_VARIABLE_API_KEY` | 是 | 无 | 在 [控制台](https://parallelvariable.com/console) 生成的个人/企业 API Key |
|
|
54
|
+
| `PARALLEL_VARIABLE_BASE_URL` | 否 | `https://api.parallelvariable.com` | 开放平台公开 API 基地址 |
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 客户端一键配置 / Client Configuration
|
|
59
|
+
|
|
60
|
+
### 1. Cursor (`~/.cursor/mcp.json` 或项目 `.cursor/mcp.json`)
|
|
61
|
+
```json
|
|
62
|
+
{
|
|
63
|
+
"mcpServers": {
|
|
64
|
+
"parallel-variable": {
|
|
65
|
+
"command": "parallel-variable-mcp",
|
|
66
|
+
"env": {
|
|
67
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 2. Claude Desktop (`claude_desktop_config.json`)
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"mcpServers": {
|
|
78
|
+
"parallel-variable": {
|
|
79
|
+
"command": "python3",
|
|
80
|
+
"args": ["-m", "parallel_variable_mcp"],
|
|
81
|
+
"env": {
|
|
82
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key"
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### 3. Antigravity / 魔搭(ModelScope)MCP 配置
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"mcpServers": {
|
|
93
|
+
"parallel-variable": {
|
|
94
|
+
"command": "parallel-variable-mcp",
|
|
95
|
+
"args": [],
|
|
96
|
+
"env": {
|
|
97
|
+
"PARALLEL_VARIABLE_API_KEY": "pv_sk_your_api_key",
|
|
98
|
+
"PARALLEL_VARIABLE_BASE_URL": "https://api.parallelvariable.com"
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## 7 个标准工具清单 / Available MCP Tools
|
|
108
|
+
|
|
109
|
+
| Tool 名称 | 是否免费 | 说明 |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| `pv_list_regions` | 免费 | 查询已开放的数字居民区域列表(如 `110105` 北京朝阳) |
|
|
112
|
+
| `pv_get_targeting_options` | 免费 | 查询标准人群定向筛选字典(性别、人群标签、学历、婚姻、收入档位) |
|
|
113
|
+
| `pv_get_account_status` | 免费 | 查询当前推演点数余额、年度点数包、套餐版本、样本/并发上限与政策白名单状态 |
|
|
114
|
+
| `pv_clarify_scenario` | 免费 | 拆解商业或社会构想,返回推荐步进单位/步数、观测目标、推荐最小年龄与能力边界 |
|
|
115
|
+
| `pv_estimate_population` | 免费 | 实时预估指定地区与筛选条件下覆盖的居民人数及防窄化提示 |
|
|
116
|
+
| `pv_run_simulation` | **扣费(需确认)** | 创建并启动推演流水线,立即返回 `pipeline_id` 与排队位置(不阻塞超时) |
|
|
117
|
+
| `pv_get_simulation_results` | 免费 | 随时查询推演进度、去重统计、社会舆情/分龄切片汇总及精选脱敏居民真实原话 |
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 安全与开源协议 / Security & License
|
|
122
|
+
|
|
123
|
+
- **开源协议**:MIT License(见 [LICENSE](./LICENSE))。
|
|
124
|
+
- **隐私与安全**:本仓库仅作为公网 API 的开源黑盒客户端,不包含任何服务端内部逻辑、模型 Prompt 或私有密钥;所有居民反馈均已在平台侧完成三层脱敏,不包含任何真实个人身份信息(PII)。
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "parallel-variable-mcp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official MCP Server for Parallel Variable (平行变量) — Let real digital residents respond to your ideas."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Parallel Variable Open Platform", email = "open-platform@parallelvariable.com" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["mcp", "model-context-protocol", "parallel-variable", "simulation", "digital-residents", "market-research", "policy-simulation"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
25
|
+
]
|
|
26
|
+
dependencies = []
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://parallelvariable.com"
|
|
30
|
+
Console = "https://parallelvariable.com/console"
|
|
31
|
+
Documentation = "https://parallelvariable.com/open-platform"
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
parallel-variable-mcp = "parallel_variable_mcp.server:main"
|
|
35
|
+
|
|
36
|
+
[tool.setuptools]
|
|
37
|
+
package-dir = { "" = "src" }
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Zero-dependency HTTP client for Parallel Variable Public Open Platform API v1."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.parallelvariable.com"
|
|
14
|
+
CONSOLE_URL = "https://parallelvariable.com/console"
|
|
15
|
+
API_PREFIX = "/api/open-platform/v1"
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("parallel_variable_mcp")
|
|
18
|
+
|
|
19
|
+
TransportFn = Callable[[str, str, dict[str, str], bytes | None, float], tuple[int, str]]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ParallelVariableApiError(RuntimeError):
|
|
23
|
+
"""Structured error returned by the Parallel Variable public API or client."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
*,
|
|
28
|
+
status_code: int,
|
|
29
|
+
code: str,
|
|
30
|
+
message: str,
|
|
31
|
+
details: dict[str, Any] | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
super().__init__(message)
|
|
34
|
+
self.status_code = status_code
|
|
35
|
+
self.code = code
|
|
36
|
+
self.message = message
|
|
37
|
+
self.details = details or {}
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict[str, Any]:
|
|
40
|
+
payload: dict[str, Any] = {
|
|
41
|
+
"status_code": self.status_code,
|
|
42
|
+
"code": self.code,
|
|
43
|
+
"message": self.message,
|
|
44
|
+
}
|
|
45
|
+
if self.details:
|
|
46
|
+
payload["details"] = self.details
|
|
47
|
+
return payload
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MissingApiKeyError(ParallelVariableApiError):
|
|
51
|
+
"""Raised when PARALLEL_VARIABLE_API_KEY is not configured."""
|
|
52
|
+
|
|
53
|
+
def __init__(self) -> None:
|
|
54
|
+
super().__init__(
|
|
55
|
+
status_code=401,
|
|
56
|
+
code="API_KEY_NOT_CONFIGURED",
|
|
57
|
+
message=(
|
|
58
|
+
"未配置 PARALLEL_VARIABLE_API_KEY 环境变量。"
|
|
59
|
+
f"请前往平行变量开放平台控制台免费领取或管理您的 API Key:{CONSOLE_URL}"
|
|
60
|
+
),
|
|
61
|
+
details={"console_url": CONSOLE_URL},
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _default_transport(
|
|
66
|
+
method: str,
|
|
67
|
+
url: str,
|
|
68
|
+
headers: dict[str, str],
|
|
69
|
+
body_bytes: bytes | None,
|
|
70
|
+
timeout: float,
|
|
71
|
+
) -> tuple[int, str]:
|
|
72
|
+
req = urllib.request.Request(url=url, data=body_bytes, headers=headers, method=method)
|
|
73
|
+
try:
|
|
74
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
75
|
+
status = getattr(resp, "status", resp.getcode())
|
|
76
|
+
raw = resp.read().decode("utf-8", errors="replace")
|
|
77
|
+
return int(status), raw
|
|
78
|
+
except urllib.error.HTTPError as exc:
|
|
79
|
+
raw = exc.read().decode("utf-8", errors="replace") if exc.fp else ""
|
|
80
|
+
return int(exc.code), raw
|
|
81
|
+
except urllib.error.URLError as exc:
|
|
82
|
+
raise ParallelVariableApiError(
|
|
83
|
+
status_code=503,
|
|
84
|
+
code="NETWORK_ERROR",
|
|
85
|
+
message=f"无法连接到平行变量开放平台服务,请检查网络或 BASE_URL 配置:{exc.reason}",
|
|
86
|
+
) from None
|
|
87
|
+
except TimeoutError:
|
|
88
|
+
raise ParallelVariableApiError(
|
|
89
|
+
status_code=504,
|
|
90
|
+
code="REQUEST_TIMEOUT",
|
|
91
|
+
message="请求平行变量开放平台超时,请稍后重试。",
|
|
92
|
+
) from None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _redact_secret(text: str, secret: str) -> str:
|
|
96
|
+
if not secret or not text:
|
|
97
|
+
return text
|
|
98
|
+
return text.replace(secret, "[REDACTED]")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _normalize_base_url(raw: str | None) -> str:
|
|
102
|
+
base = (raw or DEFAULT_BASE_URL).strip().rstrip("/")
|
|
103
|
+
if not base:
|
|
104
|
+
base = DEFAULT_BASE_URL
|
|
105
|
+
parsed = urllib.parse.urlparse(base)
|
|
106
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
107
|
+
raise ParallelVariableApiError(
|
|
108
|
+
status_code=400,
|
|
109
|
+
code="INVALID_BASE_URL",
|
|
110
|
+
message="PARALLEL_VARIABLE_BASE_URL 格式非法,必须为有效的 http(s) 地址。",
|
|
111
|
+
)
|
|
112
|
+
return base
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class ParallelVariableClient:
|
|
116
|
+
"""Black-box public API v1 client. Never logs or exposes API keys."""
|
|
117
|
+
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
*,
|
|
121
|
+
api_key: str | None = None,
|
|
122
|
+
base_url: str | None = None,
|
|
123
|
+
timeout: float = 30.0,
|
|
124
|
+
transport: TransportFn | None = None,
|
|
125
|
+
) -> None:
|
|
126
|
+
self._api_key = (
|
|
127
|
+
api_key if api_key is not None else os.environ.get("PARALLEL_VARIABLE_API_KEY", "")
|
|
128
|
+
).strip()
|
|
129
|
+
self.base_url = _normalize_base_url(
|
|
130
|
+
base_url if base_url is not None else os.environ.get("PARALLEL_VARIABLE_BASE_URL")
|
|
131
|
+
)
|
|
132
|
+
self.timeout = float(timeout)
|
|
133
|
+
self._transport = transport or _default_transport
|
|
134
|
+
|
|
135
|
+
def _require_api_key(self) -> str:
|
|
136
|
+
if not self._api_key:
|
|
137
|
+
raise MissingApiKeyError()
|
|
138
|
+
return self._api_key
|
|
139
|
+
|
|
140
|
+
def request(
|
|
141
|
+
self,
|
|
142
|
+
method: str,
|
|
143
|
+
path: str,
|
|
144
|
+
*,
|
|
145
|
+
query: dict[str, Any] | None = None,
|
|
146
|
+
json_body: dict[str, Any] | None = None,
|
|
147
|
+
) -> dict[str, Any]:
|
|
148
|
+
api_key = self._require_api_key()
|
|
149
|
+
clean_path = path if path.startswith("/") else "/" + path
|
|
150
|
+
if not clean_path.startswith(API_PREFIX):
|
|
151
|
+
clean_path = API_PREFIX + clean_path
|
|
152
|
+
|
|
153
|
+
url = self.base_url + clean_path
|
|
154
|
+
if query:
|
|
155
|
+
filtered = {k: v for k, v in query.items() if v is not None}
|
|
156
|
+
if filtered:
|
|
157
|
+
url = url + "?" + urllib.parse.urlencode(filtered)
|
|
158
|
+
|
|
159
|
+
headers = {
|
|
160
|
+
"Accept": "application/json",
|
|
161
|
+
"Authorization": f"Bearer {api_key}",
|
|
162
|
+
"User-Agent": "parallel-variable-mcp/0.1.0",
|
|
163
|
+
}
|
|
164
|
+
body_bytes: bytes | None = None
|
|
165
|
+
if json_body is not None:
|
|
166
|
+
headers["Content-Type"] = "application/json; charset=utf-8"
|
|
167
|
+
body_bytes = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
|
|
168
|
+
|
|
169
|
+
logger.debug("pv_api_request method=%s path=%s", method.upper(), clean_path)
|
|
170
|
+
status_code, raw_text = self._transport(method.upper(), url, headers, body_bytes, self.timeout)
|
|
171
|
+
safe_text = _redact_secret(raw_text, api_key)
|
|
172
|
+
|
|
173
|
+
parsed: dict[str, Any] | None = None
|
|
174
|
+
if safe_text:
|
|
175
|
+
try:
|
|
176
|
+
obj = json.loads(safe_text)
|
|
177
|
+
if isinstance(obj, dict):
|
|
178
|
+
parsed = obj
|
|
179
|
+
except json.JSONDecodeError:
|
|
180
|
+
parsed = None
|
|
181
|
+
|
|
182
|
+
if status_code >= 400:
|
|
183
|
+
err_obj = parsed.get("error") if isinstance(parsed, dict) else None
|
|
184
|
+
code = "API_ERROR"
|
|
185
|
+
message = f"请求失败(HTTP {status_code})"
|
|
186
|
+
details: dict[str, Any] = {}
|
|
187
|
+
if isinstance(err_obj, dict):
|
|
188
|
+
code = str(err_obj.get("code") or code)
|
|
189
|
+
message = _redact_secret(str(err_obj.get("message") or message), api_key)
|
|
190
|
+
for k, v in err_obj.items():
|
|
191
|
+
if k not in {"code", "message"}:
|
|
192
|
+
details[k] = v
|
|
193
|
+
if isinstance(parsed, dict) and isinstance(parsed.get("data"), dict):
|
|
194
|
+
details["data"] = parsed["data"]
|
|
195
|
+
|
|
196
|
+
if code in {"INSUFFICIENT_MINIMUM_START_BALANCE", "INSUFFICIENT_BALANCE"}:
|
|
197
|
+
details.setdefault("console_url", CONSOLE_URL)
|
|
198
|
+
message = f"{message} 请前往控制台充值:{CONSOLE_URL}"
|
|
199
|
+
elif code == "POLICY_WHITELIST_REQUIRED":
|
|
200
|
+
details.setdefault("console_url", CONSOLE_URL)
|
|
201
|
+
message = f"{message} 如需开通政企/科研公共政策推演白名单,请联系平行变量开放平台:{CONSOLE_URL}"
|
|
202
|
+
elif code == "UNAUTHENTICATED":
|
|
203
|
+
details.setdefault("console_url", CONSOLE_URL)
|
|
204
|
+
message = f"API Key 无效或已失效,请前往控制台检查或重新生成:{CONSOLE_URL}"
|
|
205
|
+
|
|
206
|
+
logger.warning("pv_api_error method=%s path=%s status=%s code=%s", method.upper(), clean_path, status_code, code)
|
|
207
|
+
raise ParallelVariableApiError(
|
|
208
|
+
status_code=status_code,
|
|
209
|
+
code=code,
|
|
210
|
+
message=message,
|
|
211
|
+
details=details,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
if parsed is None:
|
|
215
|
+
raise ParallelVariableApiError(
|
|
216
|
+
status_code=502,
|
|
217
|
+
code="INVALID_API_RESPONSE",
|
|
218
|
+
message="开放平台返回了非预期响应格式。",
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
data = parsed.get("data")
|
|
222
|
+
if isinstance(data, dict):
|
|
223
|
+
return data
|
|
224
|
+
return parsed
|
|
225
|
+
|
|
226
|
+
# ------------------------------------------------------------------
|
|
227
|
+
# Public Open Platform v1 Endpoints
|
|
228
|
+
# ------------------------------------------------------------------
|
|
229
|
+
def list_regions(self) -> dict[str, Any]:
|
|
230
|
+
return self.request("GET", "/regions")
|
|
231
|
+
|
|
232
|
+
def get_targeting_options(self) -> dict[str, Any]:
|
|
233
|
+
return self.request("GET", "/targeting/options")
|
|
234
|
+
|
|
235
|
+
def get_account_balance(self) -> dict[str, Any]:
|
|
236
|
+
return self.request("GET", "/account/balance")
|
|
237
|
+
|
|
238
|
+
def get_account_entitlements(self) -> dict[str, Any]:
|
|
239
|
+
return self.request("GET", "/account/entitlements")
|
|
240
|
+
|
|
241
|
+
def clarify_scenario(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
242
|
+
return self.request("POST", "/scenarios/clarify", json_body=payload)
|
|
243
|
+
|
|
244
|
+
def estimate_population(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
245
|
+
return self.request("POST", "/populations/plan", json_body=payload)
|
|
246
|
+
|
|
247
|
+
def create_pipeline(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
248
|
+
return self.request("POST", "/pipelines", json_body=payload)
|
|
249
|
+
|
|
250
|
+
def confirm_population(self, pipeline_id: str) -> dict[str, Any]:
|
|
251
|
+
return self.request("POST", f"/pipelines/{urllib.parse.quote(pipeline_id, safe='')}/confirm-population")
|
|
252
|
+
|
|
253
|
+
def launch_pipeline(self, pipeline_id: str) -> dict[str, Any]:
|
|
254
|
+
return self.request("POST", f"/pipelines/{urllib.parse.quote(pipeline_id, safe='')}/launch")
|
|
255
|
+
|
|
256
|
+
def get_pipeline(self, pipeline_id: str) -> dict[str, Any]:
|
|
257
|
+
return self.request("GET", f"/pipelines/{urllib.parse.quote(pipeline_id, safe='')}")
|
|
258
|
+
|
|
259
|
+
def get_pipeline_observations(
|
|
260
|
+
self,
|
|
261
|
+
pipeline_id: str,
|
|
262
|
+
*,
|
|
263
|
+
day_index: int | None = None,
|
|
264
|
+
limit: int = 100,
|
|
265
|
+
offset: int = 0,
|
|
266
|
+
) -> dict[str, Any]:
|
|
267
|
+
return self.request(
|
|
268
|
+
"GET",
|
|
269
|
+
f"/pipelines/{urllib.parse.quote(pipeline_id, safe='')}/observations",
|
|
270
|
+
query={"day_index": day_index, "limit": limit, "offset": offset},
|
|
271
|
+
)
|