-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
399 lines (351 loc) · 14.3 KB
/
Copy pathmcp_server.py
File metadata and controls
399 lines (351 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""
Property Comps MCP Server
Enables Claude, ChatGPT, and other AI agents to look up comparable property sales
across 11 global markets via the Model Context Protocol.
Install: pip install mcp httpx
Run: python mcp_server.py
Config: Add to Claude Desktop's claude_desktop_config.json or Claude Code's settings
Example queries an AI agent can answer:
- "What are comparable sales near 10001 in NYC?"
- "What's the median price in Dubai Marina?"
- "Show me price trends for SW1A in London"
- "Generate a PDF valuation report for postcode 75001 in Paris"
"""
import json
import sys
import os
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
except ImportError:
print("Installing MCP SDK...")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "mcp", "httpx", "-q"])
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import httpx
# ── Market Configuration ──
MARKETS = {
"uk": {
"name": "United Kingdom",
"base_url": "https://property.nwc-advisory.com",
"location_param": "postcode",
"location_example": "SW1A1AA",
"radius_param": "radius_miles",
"currency": "GBP",
"transactions": "31M",
},
"fr": {
"name": "France",
"base_url": "https://property-fr.nwc-advisory.com",
"location_param": "code_postal",
"location_example": "75001",
"radius_param": "radius_km",
"currency": "EUR",
"transactions": "8.3M",
},
"sg": {
"name": "Singapore",
"base_url": "https://property-sg.nwc-advisory.com",
"location_param": "postal_code",
"location_example": "310093",
"radius_param": "radius_km",
"currency": "SGD",
"transactions": "973K",
},
"nyc": {
"name": "New York City",
"base_url": "https://property-nyc.nwc-advisory.com",
"location_param": "zip_code",
"location_example": "10001",
"radius_param": "radius_miles",
"currency": "USD",
"transactions": "505K",
},
"chi": {
"name": "Chicago",
"base_url": "https://property-chi.nwc-advisory.com",
"location_param": "zip_code",
"location_example": "60606",
"radius_param": "radius_miles",
"currency": "USD",
"transactions": "282K",
},
"dxb": {
"name": "Dubai",
"base_url": "https://property-dxb.nwc-advisory.com",
"location_param": "area_name",
"location_example": "Dubai Marina",
"radius_param": "radius_km",
"currency": "AED",
"transactions": "1M",
},
"mia": {
"name": "Miami",
"base_url": "https://property-miami.nwc-advisory.com",
"location_param": "zip_code",
"location_example": "33101",
"radius_param": "radius_miles",
"currency": "USD",
"transactions": "284K",
},
"phl": {
"name": "Philadelphia",
"base_url": "https://property-phl.nwc-advisory.com",
"location_param": "zip_code",
"location_example": "19103",
"radius_param": "radius_miles",
"currency": "USD",
"transactions": "240K",
},
"ct": {
"name": "Connecticut",
"base_url": "https://property-ct.nwc-advisory.com",
"location_param": "town",
"location_example": "Greenwich",
"radius_param": "radius_miles",
"currency": "USD",
"transactions": "282K",
},
"ie": {
"name": "Ireland",
"base_url": "https://property-ie.nwc-advisory.com",
"location_param": "county",
"location_example": "Dublin",
"radius_param": "radius_km",
"currency": "EUR",
"transactions": "230K",
},
"tw": {
"name": "Taiwan",
"base_url": "https://property-tw.nwc-advisory.com",
"location_param": "city_en",
"location_example": "Taipei",
"radius_param": "radius_km",
"currency": "TWD",
"transactions": "669K",
},
}
def detect_market(location: str) -> str:
"""Auto-detect market from location format."""
loc = location.strip()
# UK postcode pattern (letters+digits+space+digit+letters)
if len(loc) >= 5 and loc[0].isalpha() and any(c.isdigit() for c in loc[:4]):
if " " in loc or len(loc) <= 8:
return "uk"
# Singapore (6 digits)
if len(loc) == 6 and loc.isdigit():
return "sg"
# 5-digit codes: distinguish US ZIP from French postal code
if len(loc) == 5 and loc.isdigit():
first2 = int(loc[:2])
first3 = loc[:3]
# US ZIP prefixes (check these first -- they overlap with French 01-95)
us_nyc = ("100", "101", "102", "103", "104", "110", "111", "112", "113", "114", "116")
us_mia = ("330", "331", "332", "333", "334", "341")
us_phl = ("190", "191", "192", "193", "194")
us_chi = ("604", "605", "606", "607", "608")
us_ct = ("060", "061", "062", "063", "064", "065", "066", "067", "068", "069")
if first3 in us_nyc:
return "nyc"
if first3 in us_mia:
return "mia"
if first3 in us_phl:
return "phl"
if first3 in us_chi:
return "chi"
if first3 in us_ct:
return "ct"
# Other US ZIPs (ranges not covered by France: 96, 99, and some others)
# French codes: 01-95, 97, 98. US ZIPs: 00-99 (overlap is total for 01-95)
# Heuristic: if first2 > 95 or first2 == 0, it's US
if first2 == 0 or first2 > 95:
return "nyc" # default US
# Remaining 5-digit codes (01-95): assume French
return "fr"
# Named locations
loc_lower = loc.lower()
if any(w in loc_lower for w in ["dubai", "marina", "jumeirah", "palm", "jbr", "downtown"]):
return "dxb"
if any(w in loc_lower for w in ["greenwich", "stamford", "hartford", "new haven", "connecticut"]):
return "ct"
if any(w in loc_lower for w in ["dublin", "cork", "galway", "limerick"]):
return "ie"
if any(w in loc_lower for w in ["taipei", "kaohsiung", "taichung", "tainan"]):
return "tw"
if any(w in loc_lower for w in ["bukit", "ang mo", "tampines", "woodlands", "jurong", "toa payoh"]):
return "sg"
return "uk" # fallback
# ── MCP Server ──
server = Server("property-comps")
@server.list_tools()
async def list_tools():
return [
Tool(
name="search_property_comps",
description=(
"Search for comparable property sales near a location. "
"Covers 11 markets: NYC, Miami, Philadelphia, Connecticut, Chicago, "
"Dubai, Singapore, London/UK, Paris/France, Ireland, Taiwan. "
"Returns recent sales with price, date, address, property type, and area. "
"Also returns statistics (median, average, min, max)."
),
inputSchema={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Postcode, ZIP code, or area name. Examples: SW1A1AA (UK), 10001 (NYC), 75001 (Paris), Dubai Marina, 310093 (Singapore)",
},
"market": {
"type": "string",
"description": "Market code (optional, auto-detected from location). One of: uk, fr, sg, nyc, chi, dxb, mia, phl, ct, ie, tw",
"enum": list(MARKETS.keys()),
},
"months": {
"type": "integer",
"description": "Look-back period in months (default: 12)",
"default": 12,
},
"radius": {
"type": "number",
"description": "Search radius in miles (UK/US) or km (others). Default: 1.0",
"default": 1.0,
},
"property_type": {
"type": "string",
"description": "Filter by type. UK: D/S/T/F. NYC: Condo/1-Family. SG: 3 ROOM/4 ROOM/5 ROOM. Optional.",
},
"limit": {
"type": "integer",
"description": "Max results (default: 10)",
"default": 10,
},
},
"required": ["location"],
},
),
Tool(
name="get_area_stats",
description=(
"Get price statistics for a property market area. "
"Returns median, average, min, max prices with breakdown by property type. "
"Covers all 11 markets."
),
inputSchema={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Postcode, ZIP code, or area name",
},
"market": {
"type": "string",
"enum": list(MARKETS.keys()),
},
"months": {
"type": "integer",
"default": 12,
},
},
"required": ["location"],
},
),
Tool(
name="list_markets",
description="List all 11 available property markets with transaction counts and examples.",
inputSchema={
"type": "object",
"properties": {},
},
),
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "list_markets":
lines = ["Available property markets:\n"]
for key, m in MARKETS.items():
lines.append(
f"- **{m['name']}** ({key}): {m['transactions']} transactions, "
f"currency {m['currency']}, example: {m['location_param']}={m['location_example']}"
)
lines.append(f"\nTotal: 4.2M+ transactions across 11 markets.")
lines.append("Data from official government registries.")
return [TextContent(type="text", text="\n".join(lines))]
location = arguments.get("location", "")
market_key = arguments.get("market") or detect_market(location)
market = MARKETS.get(market_key)
if not market:
return [TextContent(type="text", text=f"Unknown market: {market_key}. Use list_markets to see available options.")]
months = arguments.get("months", 12)
radius = arguments.get("radius", 1.0)
limit = arguments.get("limit", 10)
params = {
market["location_param"]: location,
market["radius_param"]: radius,
"months": months,
"limit": limit,
}
if arguments.get("property_type"):
params["property_type"] = arguments["property_type"]
if name == "search_property_comps":
endpoint = "/v1/comps"
elif name == "get_area_stats":
endpoint = "/v1/stats"
else:
return [TextContent(type="text", text=f"Unknown tool: {name}")]
url = f"{market['base_url']}{endpoint}"
try:
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(url, params=params)
resp.raise_for_status()
data = resp.json()
except httpx.HTTPStatusError as e:
return [TextContent(type="text", text=f"API error ({e.response.status_code}): {e.response.text[:500]}")]
except Exception as e:
return [TextContent(type="text", text=f"Connection error to {market['name']}: {str(e)}")]
# Format response
if name == "search_property_comps":
results = data.get("results", [])
stats = data.get("statistics", {})
count = data.get("count", len(results))
lines = [f"**{market['name']}** - {count} comparable sales found near {location}\n"]
if stats:
lines.append(f"**Statistics:** Median: {market['currency']} {stats.get('median', 'N/A'):,} | "
f"Average: {market['currency']} {stats.get('average', 'N/A'):,} | "
f"Range: {market['currency']} {stats.get('min', 'N/A'):,} - {market['currency']} {stats.get('max', 'N/A'):,}\n")
for i, r in enumerate(results[:limit], 1):
price = r.get("price") or r.get("sale_price") or r.get("resale_price", 0)
date = r.get("date") or r.get("sale_date", "")
address = r.get("address") or r.get("street_name", "")
ptype = r.get("property_type") or r.get("flat_type", "")
dist = r.get("distance_miles") or r.get("distance_km", "")
area = r.get("floor_area_sqm") or r.get("gross_sqft", "")
lines.append(f"{i}. {market['currency']} {price:,} | {date} | {ptype} | {address}")
if dist:
lines.append(f" Distance: {dist} | Area: {area}")
lines.append(f"\nData source: {market['name']} government property registry")
return [TextContent(type="text", text="\n".join(lines))]
elif name == "get_area_stats":
stats = data.get("stats", data.get("statistics", {}))
by_type = data.get("by_type", {})
lines = [f"**{market['name']}** - Area statistics for {location}\n"]
if stats:
lines.append(f"Median: {market['currency']} {stats.get('median', 'N/A'):,}")
lines.append(f"Average: {market['currency']} {stats.get('average', 'N/A'):,}")
lines.append(f"Min: {market['currency']} {stats.get('min', 'N/A'):,}")
lines.append(f"Max: {market['currency']} {stats.get('max', 'N/A'):,}")
lines.append(f"Transactions: {stats.get('count', 'N/A')}")
if by_type:
lines.append(f"\n**By property type:**")
for ptype, pstats in by_type.items():
lines.append(f"- {ptype}: Median {market['currency']} {pstats.get('median', 'N/A'):,} ({pstats.get('count', 0)} sales)")
return [TextContent(type="text", text="\n".join(lines))]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())