-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathHttpEndpointUtility.cs
More file actions
456 lines (400 loc) · 16.2 KB
/
HttpEndpointUtility.cs
File metadata and controls
456 lines (400 loc) · 16.2 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
using System;
using System.Net;
using MCPForUnity.Editor.Constants;
using MCPForUnity.Editor.Models;
using MCPForUnity.Editor.Services;
using UnityEditor;
namespace MCPForUnity.Editor.Helpers
{
/// <summary>
/// Helper methods for managing HTTP endpoint URLs used by the MCP bridge.
/// Ensures the stored value is always the base URL (without trailing path),
/// and provides convenience accessors for specific endpoints.
///
/// HTTP Local and HTTP Remote use separate EditorPrefs keys so that switching
/// between scopes does not overwrite the other scope's URL.
/// </summary>
public static class HttpEndpointUtility
{
private const string LocalPrefKey = EditorPrefKeys.HttpBaseUrl;
private const string RemotePrefKey = EditorPrefKeys.HttpRemoteBaseUrl;
private const string LanPublicPrefKey = EditorPrefKeys.HttpLanPublicBaseUrl;
private const string LanBindPrefKey = EditorPrefKeys.HttpLanBindBaseUrl;
private const string DefaultLocalBaseUrl = "http://127.0.0.1:8080";
private const string DefaultRemoteBaseUrl = "";
private const string DefaultLanPublicBaseUrl = "http://192.168.1.10:8090";
private const string DefaultLanBindBaseUrl = "http://0.0.0.0:8090";
/// <summary>
/// Returns the normalized base URL for the currently active HTTP scope.
/// If the scope is "remote", returns the remote URL; otherwise returns the local URL.
/// </summary>
public static string GetBaseUrl()
{
if (IsRemoteScope()) return GetRemoteBaseUrl();
if (IsLanScope()) return GetLanPublicBaseUrl();
return GetLocalBaseUrl();
}
/// <summary>
/// Saves a user-provided URL to the currently active HTTP scope's pref.
/// </summary>
public static void SaveBaseUrl(string userValue)
{
if (IsRemoteScope())
{
SaveRemoteBaseUrl(userValue);
}
else if (IsLanScope())
{
SaveLanPublicBaseUrl(userValue);
}
else
{
SaveLocalBaseUrl(userValue);
}
}
/// <summary>
/// Returns the normalized local HTTP base URL (always reads local pref).
/// </summary>
public static string GetLocalBaseUrl()
{
string stored = EditorPrefs.GetString(LocalPrefKey, DefaultLocalBaseUrl);
return NormalizeBaseUrl(stored, DefaultLocalBaseUrl, remoteScope: false);
}
/// <summary>
/// Saves a user-provided URL to the local HTTP pref.
/// </summary>
public static void SaveLocalBaseUrl(string userValue)
{
string normalized = NormalizeBaseUrl(userValue, DefaultLocalBaseUrl, remoteScope: false);
EditorPrefs.SetString(LocalPrefKey, normalized);
}
/// <summary>
/// Returns the normalized remote HTTP base URL (always reads remote pref).
/// Returns empty string if no remote URL is configured.
/// </summary>
public static string GetRemoteBaseUrl()
{
string stored = EditorPrefs.GetString(RemotePrefKey, DefaultRemoteBaseUrl);
if (string.IsNullOrWhiteSpace(stored))
{
return DefaultRemoteBaseUrl;
}
return NormalizeBaseUrl(stored, DefaultRemoteBaseUrl, remoteScope: true);
}
/// <summary>
/// Returns the normalized LAN public URL that remote clients should use.
/// </summary>
public static string GetLanPublicBaseUrl()
{
string stored = EditorPrefs.GetString(LanPublicPrefKey, DefaultLanPublicBaseUrl);
return NormalizeBaseUrl(stored, DefaultLanPublicBaseUrl, remoteScope: false);
}
/// <summary>
/// Saves the LAN public URL and keeps the bind URL on 0.0.0.0 with the same port.
/// </summary>
public static void SaveLanPublicBaseUrl(string userValue)
{
string normalized = NormalizeBaseUrl(userValue, DefaultLanPublicBaseUrl, remoteScope: false);
EditorPrefs.SetString(LanPublicPrefKey, normalized);
if (Uri.TryCreate(normalized, UriKind.Absolute, out var uri) && uri.Port > 0)
{
EditorPrefs.SetString(LanBindPrefKey, $"http://0.0.0.0:{uri.Port}");
}
}
/// <summary>
/// Returns the LAN bind URL used to launch the local server.
/// </summary>
public static string GetLanBindBaseUrl()
{
string stored = EditorPrefs.GetString(LanBindPrefKey, DefaultLanBindBaseUrl);
return NormalizeBaseUrl(stored, DefaultLanBindBaseUrl, remoteScope: false);
}
/// <summary>
/// Returns the URL used to launch/probe/stop the local server process.
/// LAN mode binds all interfaces while exposing a separate public client URL.
/// </summary>
public static string GetLocalServerLaunchBaseUrl()
{
return IsLanScope() ? GetLanBindBaseUrl() : GetLocalBaseUrl();
}
/// <summary>
/// Saves a user-provided URL to the remote HTTP pref.
/// </summary>
public static void SaveRemoteBaseUrl(string userValue)
{
if (string.IsNullOrWhiteSpace(userValue))
{
EditorPrefs.SetString(RemotePrefKey, DefaultRemoteBaseUrl);
return;
}
string normalized = NormalizeBaseUrl(userValue, DefaultRemoteBaseUrl, remoteScope: true);
EditorPrefs.SetString(RemotePrefKey, normalized);
}
/// <summary>
/// Builds the JSON-RPC endpoint for the currently active scope (base + /mcp).
/// </summary>
public static string GetMcpRpcUrl()
{
return AppendPathSegment(GetBaseUrl(), "mcp");
}
/// <summary>
/// Builds the local JSON-RPC endpoint (local base + /mcp).
/// </summary>
public static string GetLocalMcpRpcUrl()
{
return AppendPathSegment(GetLocalBaseUrl(), "mcp");
}
/// <summary>
/// Builds the LAN public JSON-RPC endpoint (public base + /mcp).
/// </summary>
public static string GetLanMcpRpcUrl()
{
return AppendPathSegment(GetLanPublicBaseUrl(), "mcp");
}
/// <summary>
/// Builds the remote JSON-RPC endpoint (remote base + /mcp).
/// Returns empty string if no remote URL is configured.
/// </summary>
public static string GetRemoteMcpRpcUrl()
{
string remoteBase = GetRemoteBaseUrl();
return string.IsNullOrEmpty(remoteBase) ? string.Empty : AppendPathSegment(remoteBase, "mcp");
}
/// <summary>
/// Builds the endpoint used when POSTing custom-tool registration payloads.
/// </summary>
public static string GetRegisterToolsUrl()
{
return AppendPathSegment(GetBaseUrl(), "register-tools");
}
/// <summary>
/// Returns true if the active HTTP transport scope is "remote".
/// </summary>
public static bool IsRemoteScope()
{
string scope = EditorConfigurationCache.Instance.HttpTransportScope;
return string.Equals(scope, "remote", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Returns true if the active HTTP transport scope is "lan".
/// </summary>
public static bool IsLanScope()
{
string scope = EditorConfigurationCache.Instance.HttpTransportScope;
return string.Equals(scope, "lan", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Returns the <see cref="ConfiguredTransport"/> that matches the current server-side
/// transport selection (Stdio, Http, or HttpRemote).
/// Centralises the 3-way determination so callers avoid duplicated logic.
/// </summary>
public static ConfiguredTransport GetCurrentServerTransport()
{
bool useHttp = EditorConfigurationCache.Instance.UseHttpTransport;
if (!useHttp) return ConfiguredTransport.Stdio;
if (IsLanScope()) return ConfiguredTransport.HttpLan;
return IsRemoteScope() ? ConfiguredTransport.HttpRemote : ConfiguredTransport.Http;
}
/// <summary>
/// Returns true when advanced settings allow binding HTTP Local to all interfaces
/// (e.g. 0.0.0.0 / ::). Disabled by default.
/// </summary>
public static bool AllowLanHttpBind()
{
return EditorPrefs.GetBool(EditorPrefKeys.AllowLanHttpBind, false);
}
/// <summary>
/// Returns true when advanced settings allow insecure HTTP/WS for remote endpoints.
/// Disabled by default.
/// </summary>
public static bool AllowInsecureRemoteHttp()
{
return EditorPrefs.GetBool(EditorPrefKeys.AllowInsecureRemoteHttp, false);
}
/// <summary>
/// Returns true if the host is loopback-only.
/// </summary>
public static bool IsLoopbackHost(string host)
{
if (string.IsNullOrWhiteSpace(host))
{
return false;
}
string normalized = host.Trim().Trim('[', ']').ToLowerInvariant();
if (normalized == "localhost")
{
return true;
}
if (IPAddress.TryParse(normalized, out IPAddress parsedIp))
{
return IPAddress.IsLoopback(parsedIp);
}
return false;
}
/// <summary>
/// Returns true if the host is a bind-all-interfaces address.
/// </summary>
public static bool IsBindAllInterfacesHost(string host)
{
if (string.IsNullOrWhiteSpace(host))
{
return false;
}
string normalized = host.Trim().Trim('[', ']').ToLowerInvariant();
if (IPAddress.TryParse(normalized, out IPAddress parsedIp))
{
return parsedIp.Equals(IPAddress.Any) || parsedIp.Equals(IPAddress.IPv6Any);
}
return false;
}
/// <summary>
/// Returns true when the URL host is acceptable for HTTP Local launch.
/// Loopback is always allowed. Bind-all interfaces requires explicit opt-in.
/// </summary>
public static bool IsHttpLocalUrlAllowedForLaunch(string url, out string error)
{
error = null;
if (string.IsNullOrWhiteSpace(url))
{
error = "HTTP Local requires a loopback URL (localhost/127.0.0.1/::1).";
return false;
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
error = $"Invalid URL: {url}";
return false;
}
string host = uri.Host;
if (IsLoopbackHost(host))
{
return true;
}
if (IsBindAllInterfacesHost(host))
{
if (AllowLanHttpBind())
{
return true;
}
error = "Binding to all interfaces (0.0.0.0/::) is disabled by default. " +
"Enable \"Allow LAN bind for HTTP Local\" in Advanced Settings to opt in.";
return false;
}
error = "HTTP Local requires a loopback URL (localhost/127.0.0.1/::1).";
return false;
}
/// <summary>
/// Returns true when the URL is acceptable for LAN HTTP launch.
/// LAN mode intentionally binds all interfaces for trusted private networks.
/// </summary>
public static bool IsHttpLanUrlAllowedForLaunch(string url, out string error)
{
error = null;
if (string.IsNullOrWhiteSpace(url))
{
error = "LAN HTTP requires a bind URL such as http://0.0.0.0:8090.";
return false;
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
error = $"Invalid LAN HTTP bind URL: {url}";
return false;
}
if (!uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
{
error = "LAN HTTP bind URL must use http://.";
return false;
}
if (uri.Port <= 0)
{
error = "LAN HTTP bind URL requires an explicit port.";
return false;
}
if (IsBindAllInterfacesHost(uri.Host))
{
return true;
}
error = "LAN HTTP server bind host must be 0.0.0.0 or ::.";
return false;
}
/// <summary>
/// Returns true when remote URL is allowed by current security policy.
/// HTTPS is required by default; HTTP needs explicit opt-in.
/// </summary>
public static bool IsRemoteUrlAllowed(string remoteBaseUrl, out string error)
{
error = null;
if (string.IsNullOrWhiteSpace(remoteBaseUrl))
{
error = "HTTP Remote requires a configured URL.";
return false;
}
if (!Uri.TryCreate(remoteBaseUrl, UriKind.Absolute, out var uri))
{
error = $"Invalid HTTP Remote URL: {remoteBaseUrl}";
return false;
}
if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
{
if (AllowInsecureRemoteHttp())
{
return true;
}
error = "HTTP Remote requires HTTPS by default. Enable \"Allow insecure HTTP for HTTP Remote\" in Advanced Settings to opt in.";
return false;
}
error = $"Unsupported URL scheme '{uri.Scheme}'. Use https:// (or http:// only with explicit insecure opt-in).";
return false;
}
/// <summary>
/// Returns true when the currently configured remote URL satisfies security policy.
/// </summary>
public static bool IsCurrentRemoteUrlAllowed(out string error)
{
return IsRemoteUrlAllowed(GetRemoteBaseUrl(), out error);
}
/// <summary>
/// Human-readable host requirement for HTTP Local based on current security settings.
/// </summary>
public static string GetHttpLocalHostRequirementText()
{
return AllowLanHttpBind()
? "localhost/127.0.0.1/::1/0.0.0.0/::"
: "localhost/127.0.0.1/::1";
}
/// <summary>
/// Normalizes a URL so that we consistently store just the base (no trailing slash/path).
/// </summary>
private static string NormalizeBaseUrl(string value, string defaultUrl, bool remoteScope)
{
if (string.IsNullOrWhiteSpace(value))
{
return defaultUrl;
}
string trimmed = value.Trim();
// Ensure scheme exists.
// For HTTP Remote, default to https:// to avoid accidental plaintext transport.
// For HTTP Local, default to http:// for zero-friction local setup.
if (!trimmed.Contains("://"))
{
string defaultScheme = remoteScope ? "https" : "http";
trimmed = $"{defaultScheme}://{trimmed}";
}
// Remove trailing slash segments.
trimmed = trimmed.TrimEnd('/');
// Strip trailing "/mcp" (case-insensitive) if provided.
if (trimmed.EndsWith("/mcp", StringComparison.OrdinalIgnoreCase))
{
trimmed = trimmed[..^4];
}
return trimmed;
}
private static string AppendPathSegment(string baseUrl, string segment)
{
return $"{baseUrl.TrimEnd('/')}/{segment}";
}
}
}